关于前端:Action和Reducer的编写-增添功能

6次阅读

共计 2542 个字符,预计需要花费 7 分钟才能阅读完成。

1、主体页面内容革新
接下来,咱们应用 action 和 reducer,来对这个组件的数据进行前后传递。首先,先来革新 TodoList.js 文件。具体代码如下:

import React, {Component} from ‘react’;
import ‘antd/dist/antd.css’;
import {Input, Button, List} from ‘antd’;
import store from ‘./store’;

class TodoList 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.subscribe(this.handleStoreChange)
}
render() {
return (
<div style={{marginTop: ’10px’, marginLeft: ’10px’}}>
<div>
<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={{marginTop: ’10px’, width: ‘300px’}}
bordered
dataSource={this.state.list}
renderItem={item => <List.Item>{item}</List.Item>}
/>
</div>
)
}

handleInputChange(e) {
// 在 react 中,action 是一个对象的模式
// type 旨在通知 react 说,你帮我去扭转 input 的值,这个值是上面的 value,也就是 e.target.value
const action = {
type: ‘change_input_value’,
value: e.target.value
}
store.dispatch(action)
// console.log(e.target.value)
}

handleStoreChange() {
// 当感知到 store 的数据发生变化时,那么就去调用 store.getState 办法,从 store 外面再从新取一次数据,
// 而后去调用 setState,替换掉以后 store 外面的数据
this.setState(store.getState())
}

handleBtnClick() {
const action = {
type: ‘add_todo_item’
}
store.dispatch(action)
}
}

export default TodoList;

接下来咱们来剖析以上代码。首先,每一个动作别离会先去绑定对应的事件,之后呢,在事件外面,去发明 action。而对于发明的 action 来说,它旨在通知 react,让 react 去帮忙 action 去扭转某个值,而这个值就是它绑定的 value。前端培训

最初,action 要做的事件完结了,那么它的数据就须要去存储到 store 外面。于是通过 store.dispatch(action) 来进行解决,将 action 的数据传递到 store 外面。

2、扭转 action 中的数据
对于 action 一开始的值来说,它是固定的。但有时候咱们是想要去批改 action 中的值,这个时候就须要用到 reducer。当初,咱们来革新下 reducer.js 文件,让 input 框能够自在的输出值,同时,点击提交按钮之后,进行列表的削减操作。具体代码如下:

const defaultStore = {
inputValue: ‘123’,
list: [1, 2]
};

// reducer 能够接管 state,然而绝不能批改 state
const reducer = (state = defaultStore, 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 = ”;
console.log(newState);
return newState;
}
return state;
}
export default reducer;

3、store 数据革新
上面,咱们来看下 store 文件夹下 index.js 的内容。咱们须要对其进行简略的革新,具体代码如下:

import {createStore} from “redux”;
import reducer from ‘./reducer’;

const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

export default store;

除了 reducer 之外,咱们还要将 window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() 给传递进去并调用这个办法。

正文完
 0