一、index.js
import React from 'react'
import ReactDOM from 'react-dom'
import TodoList from './TodoList'
import { Provider } from 'react-redux'
import store from './store'
// Provider(生产者)把store提供给内部所有组件
const App = () => {
<Provider store={store}>
<TodoList />
</Provider>
}
ReactDOM.render(App, document.getElementById('root'))
二、TodoList.js
import React, {Component} from 'react'
import { connect } from 'react-redux'
import {
getInputChangeAction,
getButClickAction,
getDeleteItem,
getTodoList,
getInitList
} from './store/actionCreators';
// 此时TodoList只是一个UI组件,同时也是一个无状态组件,只负责页面的渲染,有效提升代码性能
const TodoList = (props) => {
render(){
const { inputValue,
changeInputValue,
hendleClick,
handleDelete,
} = props
return(
<div>
<div>
<input
value={inputValue}
onChange={changeInputValue}
/>
<button onClick={hendleClick}>提交</button>
</div>
<ul>
{
this.props.list.map((item,index)=>{
<li
key={index}
onClick={handleDelete(index)}
>
{item}
</li>
})
}
</ul>
</div>
)
}
}
// 让ToDoList和store进行连接
// 第一个参数意思:把store里面的数据映射给组件的props
const mapStateToProps = (state) => {
return {
inputValue:state.inputValue,
list:state.list
}
}
// 第二个参数意思: 把store中的dispatch方法挂载到props上
const mapDispatchProps= (dispatch) => {
return {
changeInputValue(e){
const action = getInputChangeAction(e.target.value)
dispatch(action)
},
hendleClick(){
const action = getButClickAction()
dispatch(action)
},
handleDelete(){
const action = getDeleteItem(index)
dispatch(action)
}
}
}
//数据变页面就会跟着变,不用再做订阅
export default connect(mapStateToProps, mapDispatchProps)(ToDoList);
三、store/index.js
import { createStore } from 'redux';
import reducer from './reducer';
//创建一个公共存储仓库
const store = createStore(reducer),
export default store;
四、store/reducer.js
import { CHANGE_INPUT_VALUE, CHANGE_LIST_VALUE, DELETE_LIST_ITEM, INIT_LIST_ACTION } from './actionTypes';
const defaultState = {
inputValue: '',
list: []
}
//默认数据
export default (state = defaultState, action) => {
//state是整个仓库存储的数据,action是store传递来的一个对象
if (action.type === CHANGE_INPUT_VALUE) {
return [...state, inputValue:action.value]
}
if (action.type === CHANGE_LIST_VALUE) {
const newState = JSON.parse(JSON.stringify(state))
newState.list.push(newState.inputValue)
newState.inputValue = ''
return newState
}
if (action.type === DELETE_LIST_ITEM) {
const newState = JSON.parse(JSON.stringify(state))
newState.list.splice(action.index, 1)
return newState
}
return state
}
//reducer可以接受state,但是绝对不能改变state
//reducer.js返回一个数据和方法
五、store/actionCreators.js
import {
CHANGE_INPUT_VALUE,
CHANGE_LIST_VALUE,
DELETE_LIST_ITEM,
} from './actionTypes';
import axios from 'axios'
export const getInputChangeAction = (value) =>({
type:CHANGE_INPUT_VALUE,
value:value
})
export const getButClickAction = ()=>({
type:CHANGE_LIST_VALUE,
})
export const getDeleteItem = (index) =>({
type:DELETE_LIST_ITEM,
index
})
六、store/actionTypes.js
export const CHANGE_INPUT_VALUE = 'change_input_value';
export const CHANGE_LIST_VALUE = 'change_list_value';
export const DELETE_LIST_ITEM = 'delete_list_item'