1、在src下创建redux文件夹,并新建store.js
// store.js
import { createStore } from 'redux';
import reducers from './reducers/index';
export default createStore(reducers);
2、接着在redux文件下创建reducers文件夹,并新建index.js
//index.js
//combineReducers方法,用于 Reducer 的拆分,便于以后添加其他函数
import { combineReducers } from "redux";
import { todo } from "./todo.js";
export default combineReducers({
todo
});
//todo.js
//只做了对数组增和删两个操作
const initialState = {
list:[]
}
export function todo(state = initialState, action){
if(action.type==="ADD_TODO"){
let newState = JSON.parse(JSON.stringify(state));
newState.list.push({
content:action.payload
});
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、接着去项目的index.js文件,使用Provider组件
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
//引入相关文件,并对根组件进行包裹,传入store
//这样一来,App的所有子组件就默认都可以拿到state了
import { Provider } from "react-redux";
import store from "./redux/store";
ReactDOM.render(
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>,
document.getElementById('root')
);
reportWebVitals();
4、组件里使用store
//todoList.jsx
import React, { Component } from 'react';
//1、引入connect
import { connect } from 'react-redux'
class TodoList extends Component {
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 {
deleteTodo(index){
dispatch({
type:"DEL_TODO",
payload:index
})
}
}
}
//4、connect方法接受两个参数:mapStateToProps和mapDispatchToProps,没有则传null
export default connect(mapStateToProps,mapDispatchToProps)(TodoList);