react-redux 相关步骤
- npm install react-redux --save 在项目中导入react-rudux包
- 创建reducer文件
const LOGIN_IN = '登陆';
// 创建一个reducer对象
export function auth(state={isAuth:false,name:'dan'},action){
switch (action.type){
case LOGIN_IN:
return {...state,isAuth:true,name:'lidazhou'}
break;
default:
return state;
break;
}
}
// action函数
export function login(){
return {type:LOGIN_IN}
}
import { combineReducers } from 'redux';
import {app} from './app.redux';
import { auth} from './Auth.redux';
import {list } from './todo.redux'
export default combineReducers({app,auth,list})
- 在index.js中,引入Provider,reducers,createStore
import {Provider} from 'react-redux';
import reducers from './reducers';
import {createStore} from 'redux';
// 创建store对象
const store = createStore(reducers);
// 组建中用provider包住
ReactDOM.render(
(
<Provider store={store}>
<TodoList />
</Provider>
),document.getElementById('root'));
import { connect } from 'react-redux';
import {add,sub} from './app.redux';
import {login} from './Auth.redux'
// 将store中的值state传入到组件的props中
const maptostate = (state) =>{
return ({state:state})
}
// 将reducers中的方法传入到组件的props中
const maptoaction = {add,sub,login};
class App extends Component {
constructor(props){
super(props);
}
render() {
// const store = this.props.store;
return (
<div>
<h1>{this.props.state.app}</h1>
// dispatch 一个action
<button onClick={this.props.add}>增加</button>
<button onClick={this.props.sub}>减少</button>
<button onClick={()=>this.logAllData()}>打印数据</button>
<h1>{this.props.state.auth.name}</h1>
<button onClick={this.props.login}>登陆</button>
</div>
);
}
logAllData(){
console.log('jjjjj')
console.log(this.props.state)
}
}
// store,action 之间的建立联系
App = connect(maptostate,maptoaction)(App)
export default App;
网友评论