redux在React中的作用类似于vue的vuex用作全局状态管理。其基本的使用流程如下:
- 下载redux
- 在项目中新建一个store文件夹,其中包括了:state.js、reducer.js、actionCreator.js。
- 在store.js中使用redux的createStore(reducer)来创建store。注意:必须要关联相应的reducer作为参数
import {createStore} from "redux" import reducer from "./reducer" const store=createStore(reducer); export default store;
-
在state.js中添加项目中需要的数据,state是一个对象存放项目中需要共享的数据。
const state={ numb:0 } export default state
-
在actionCreator.js中创建需要的action,然后调用store.dispatch(action)把创建的action发送给reducer。
import store from "./store" import reducer from "./reducer"; const actionCreator={ add(){ let action={ type:1, } console.log(action); store.dispatch(action); }, reducement(){ let action={ type:2, } store.dispatch(action); } } export default actionCreator;
-
编写reducer.js。reducer类似于处理器,根据不同的action来做出相应的逻辑处理,最后返回修改过后的state数据。
import state from "./state" const reducer=(prevState=state,action)=>{ let newData={...prevState}; console.log(newData) switch(action.type){ case 1: newData.numb++; break; case 2: newData.numb-- break; } console.log(newData) return newData; } export default reducer;
-
在组件中使用store.getState()来获取state.js中的数据。
import React,{NavLink} from "react" import "../style/home.css" import {withRouter} from "react-router-dom" import HomeSon from "./HomeSon" import actionCreator from "../store/actionCreator" import store from "../store/store" class Home extends React.Component{ constructor(props){ super(props) this.state={ parentText:"好好学习,天天向上", sonText:"", result:store.getState().numb } } componentWillMount(){ store.subscribe(()=>{ this.setState({result:store.getState().numb}) }) console.log(store.getState()); } show(){ return this.props.match.params.id; } add(){ actionCreator.add(); console.log("add") } send=()=>{ console.log(this); this.props.history.push('/Login'); } fun(text){ this.setState({ sonText:text }) } render(){ let {result}=this.state return( <div className="home"> <h1>我的home页面</h1> <h2>{this.show()}</h2> <div onClick={this.send}>发送</div> <HomeSon parentText={this.state.parentText} onSubmit={this.fun.bind(this)}></HomeSon> <p>来自子组件的文字:{this.state.sonText}</p> <button onClick={this.add}>增加</button> <p>state的数据:{result}</p> </div> ) } } export default Home;
他们之间的关系如下图: