其他分享
首页 > 其他分享> > react-redux得基本用法

react-redux得基本用法

作者:互联网

1.创建store

import { createStore } from 'redux'; import reducers from '../reducers/index'; export default createStore(reducers);

2.reducer(接受state和action并返回新的state)

 

import { combineReducers } from "redux"; import { todo } from "./todo.js";
export default combineReducers({   todo });           const initialState = {     list:[] } export function todo(state = initialState, action){     console.log(action.payload);     if(action.type==="ADD_TODO"){         console.log("=======add=========");         let newState = JSON.parse(JSON.stringify(state));         newState.list.push({         content:action.payload         });         console.log(newState);         return newState;     }else if(action.type==="DEL_TODO"){         let newState = JSON.parse(JSON.stringify(state));         newState.list.splice(action.payload, 1);         return newState;     }else{         return state;     } }  

3.使用Provider组件


import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import {HashRouter as Router,Route,Redirect,Switch} from "react-router-dom" import { Provider } from "react-redux"; import store from "./store";
ReactDOM.render(   <Provider store={store}>     <Router>       <Switch>         <Route path="/admin" component={App}/>          <Redirect to="/admin" from="/" exact/>           <Redirect to="/404" />       </Switch>     </Router>   </Provider>,   document.getElementById('root') );

4.组件里使用store

import React, { Component } from 'react' import { connect } from 'react-redux' class TodoList extends Component {   componentWillMount () {     console.log(this.props)     this.props.addTodo();   }   handleDelete(index){     this.props.deleteTodo(index);   }   render() {     return (       <div>         <ul>           {             this.props.list.map((item,index)=>{               return (                 <li key={index}>                   <span>{item.content}</span>                   <button onClick={this.handleDelete.bind(this,index)}>x</button>                 </li>               )             })           }         </ul>       </div>     )   } } //2、把state里的数据映射到props里,可以通过Props使用 const mapStateToProps = (state) =>{   return {     list:state.todo.list   } } //3、把action里的方法绑定到props上,可以通过Props使用,用于修改store里的数据 const mapDispatchToProps =(dispatch)=>{   return {     addTodo(){       dispatch({         type:"ADD_TODO",         payload:'1111111'       })     },     deleteTodo(index){       dispatch({         type:"DEL_TODO",         payload:index       })     }   } }
//4、connect方法接受两个参数:mapStateToProps和mapDispatchToProps,没有则传null export default connect(mapStateToProps,mapDispatchToProps)(TodoList);    

组件里使用store

标签:index,return,newState,用法,react,state,action,import,redux
来源: https://www.cnblogs.com/1024L/p/15329001.html