一、安装redux
npm i redux
二、在src下创建store文件夹
index.js文件
import { createStore } from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
export default store
reducer.js
const defaultState = {
inputValue: '123',
list: [1, 2]
}
// reducer可以接受state,但是不能修改state
export default (state = defaultState, action) => {
return state
}
组件AntTodolist.js
import React, { Component, Fragment } from 'react'
import 'antd/dist/antd.css'
import { Input, Button, List } from 'antd'
import store from '../store'
export default class AntTodolist extends Component {
constructor(props) {
super(props)
this.state = store.getState()
this.handleInputChange = this.handleInputChange.bind(this)
this.handleStoreChange = this.handleStoreChange.bind(this)
this.handleBtnClick = this.handleBtnClick.bind(this)
// 当store中数据方法变化时,订阅handleStoreChange事件
store.subscribe(this.handleStoreChange)
}
render() {
return (
<Fragment>
<div style={{ marginLeft: '10px', marginTop: '10px' }}>
<Input
value={this.state.inputValue}
placeholder="todo info"
style={{ width: '300px', marginRight: '10px' }}
onChange={this.handleInputChange}
/>
<Button type="primary" onClick={this.handleBtnClick}>提交</Button>
</div>
<List
style={{ width: '300px', marginTop: '10px', marginLeft: '10px' }}
bordered
dataSource={this.state.list}
renderItem={item => (<List.Item>{item}</List.Item>)}
/>
</Fragment>
)
}
handleInputChange(e) {
const action = {
type: 'change_input_value',
value: e.target.value
}
store.dispatch(action)
}
// 改变该组件的state值
handleStoreChange() {
this.setState(store.getState())
}
handleBtnClick () {
// 组件之中触发acition
const action = {
type: 'add_todo_item'
}
store.dispatch(action)
}
}
当组件dispatch(action)时,reducer对action进行处理
reducer.js
const defaultState = {
inputValue: '123',
list: [1, 2]
}
// reducer可以接受state,但是不能修改state
export default (state = defaultState, action) => {
if (action.type === 'change_input_value') {
const newState = JSON.parse(JSON.stringify(state))
newState.inputValue = action.value
return newState
}
if (action.type === 'add_todo_item') {
const newState = JSON.parse(JSON.stringify(state))
newState.list.push(newState.inputValue)
newState.inputValue = ''
return newState
}
return state
}
store处理state数据变化
在组件中订阅handleStoreChange事件,当store中数据方法变化时,触发handleStoreChange事件,在该事件中改变组件中state的值。
扫描二维码关注公众号,回复:
4953299 查看本文章