【发布时间】:2019-05-15 05:08:31
【问题描述】:
index.js
class App extends Component {
onClick = () => {
this.props.update()
}
componentWillReceiveProps() {
console.log('componentWillReceiveProps')
}
render() {
return (
<React.Fragment>
<h1>{this.props.foo.foo}</h1>
<button onClick={this.onClick}>Click Me!</button>
</React.Fragment>
);
}
}
const action = dispatch => {
dispatch({ type: 'foo', foo: 'first' })
dispatch({ type: 'foo', foo: 'second' })
}
const mapStateToProps = ({ foo }) => ({ foo })
const mapDispatchToProps = dispatch => ({
update: () => action(dispatch)
})
const ReduxApp = connect(mapStateToProps, mapDispatchToProps)(App);
render(
<Provider store={store}>
<ReduxApp/>
</Provider>,
document.getElementById('root')
)
redux.js
const foo = (state = {}, { type, foo }) => {
if (type === 'foo') {
return { foo }
} else {
return state
}
}
const reducer = combineReducers({ foo })
const store = { foo: '' }
export default createStore(reducer, store, applyMiddleware(thunk))
我知道 componentWillReceiveProps 已被弃用,但我们使用的是旧版本的 react,我们的代码依赖此方法。
我们之前遇到了一个非常奇怪的问题,在上面的代码中,componentWillReceiveProps 只被调用一次,但是如果我们在 index.js 中更改这一行:
dispatch({ type: 'foo', foo: 'second' })
到这里:
setTimeout(() => dispatch({ type: 'foo', foo: 'second' }), 1000)
然后 componentWillReceiveProps 被调用两次。为什么?为什么并排调度 2 个动作会导致该方法被调用一次但设置计时器会调用它两次?
【问题讨论】:
标签: reactjs redux react-redux redux-thunk