【问题标题】:ComponentWillReceiveProps Called Once With Multiple Sync Dispatches but Called Multiple Times With Async Dispatches?ComponentWillReceiveProps 使用多个同步调度调用一次,但使用异步调度调用多次?
【发布时间】: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


    【解决方案1】:

    是的,这是因为如果更新是在 React 事件处理程序中引起的,React 会批量更新。调度 Redux 操作最终会导致调用 setState()。因此,在第一种情况下,两个分派的操作都会导致一个 React 重新渲染。在第二种情况下,它会导致两次 React 重新渲染。

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 2015-12-31
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      相关资源
      最近更新 更多