如何使用redux
1.在src index.js
复制 import React from 'react';
import ReactDOM from 'react-dom'
import App from './components/app.jsx'
import store from './redux/store'
function render() {
ReactDOM.render(<App store={store} />,document.getElementById('root'))
}
render()
store.subscribe(() =>{
render()
})
2.在src目录下新建redux文件夹
3.在redux目录下新建store.js,reducers.js,actions,action_type.js
store.js
复制 import {createStore} from 'redux'
import {counter} from './reducers.js'
const store = createStore(counter);
console.log(store,store.getState())
export default store
reducers.js
复制import {INCREMENT,DECREMENT} from './action_type.js'
export const counter = (state =0,action) =>{
console.log('counter',state,action)
switch (action.type) {
case INCREMENT:
return state + action.data
case DECREMENT:
return state - action.data
default:
return state
}
}
actions.js
复制 import {INCREMENT,DECREMENT} from './action_type'
export const increment =(number) => ({type:INCREMENT,data:number})
export const decrement =(number) => ({type:DECREMENT,data:number})
action_type.js
复制export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
app.jsx(src >components >app.jsx)
复制import React, { Component } from 'react';
import * as actions from '../redux/actions'
export default class App extends Component {
increment = () =>{
const number = this.selsectVal.value*1
this.props.store.dispatch(actions.increment(number))
}
decrement =() =>{
const number = this.selsectVal.value*1
this.props.store.dispatch(actions.decrement(number))
}
incrementIfOdd =() =>{
const number = this.selsectVal.value*1;
const count = this.props.store.getState()
if(count % 2 ===1){
this.props.store.dispatch(actions.increment(number))
}
}
incrementAsync =() =>{
const number = this.selsectVal.value*1
setTimeout(() => {
this.props.store.dispatch(actions.increment(number))
}, 200);
}
render(){
const count = this.props.store.getState();
return (
<div>
<p>click {count} times</p>
<div>
<select ref={val => this.selsectVal = val}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<button onClick={this.incrementIfOdd}>increment if odd</button>
<button onClick={this.incrementAsync}>increment async</button>
</div>
</div>
)
}
}
问题
1.redux与react组件的代码耦合度太高
2.代码不够简洁
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix