store.subscribe 执行了两次
来源:5-5 Action 和 Reducer 的编写
firefox700101
2022-01-20
你好,我用了和你一样的代码,可是为什么我在 input 输入框中输入一个字母时,监听 store 变化的函数 handleStoreChange 被调用了两次呢?下面是我的代码
**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.js =======================**
const defaultState = {
inputValue: '123',
list: [1, 2]
}
// reducer 可以接收 state, 但是绝不能修改 state
const reducer = (state = defaultState, action) => {
if (action.type === 'change_input_value') {
// 深拷贝原有 state 数据
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState;
}
// state: 数据
return state;
}
export default reducer;
**TodoList.js ==========================**
import React, { Component, Fragment } from "react";
// antd
import { Input, Button, List } from 'antd';
// store
import store from "./store";
// const data = [
// 'Racing car sprays burning fuel into crowd.',
// 'Japanese princess to wed commoner.',
// 'Australian walks 100km after outback crash.',
// 'Man charged over missing wedding girl.',
// 'Los Angeles battles huge wildfires.',
// ];
class TodoList extends Component {
constructor (props) {
super(props);
this.state = store.getState();
this.handleStoreChange = this.handleStoreChange.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
store.subscribe(this.handleStoreChange);
}
handleInputChange (e) {
const action = {
type: 'change_input_value',
value: e.target.value
}
store.dispatch(action);
}
handleStoreChange () {
console.log('store changed' + Math.random(10)*10+1);
}
render () {
return (
<Fragment>
<div
style={{margin: '10px'}}
>
<Input
value={this.state.inputValue}
placeholder='todo info'
style={{width: '300px', marginRight: '10px'}}
onChange={this.handleInputChange}
/>
<Button type='primary'>提交</Button>
<List
style={{marginTop: '10px'}}
header={<div>Header</div>}
footer={<div>Footer</div>}
bordered
dataSource={this.state.list}
renderItem={item => (<List.Item>{item}</List.Item>)}
></List>
</div>
</Fragment>
);
}
}
export default TodoList
写回答
1回答
-
Dell
2022-01-23
你先确认下,是否是每次输入都打印两次,还是只有第一次的时候
022022-05-01
相似问题