ComponentWillReceiveProps使用多个同步调度调用一次,但是使用异步调度多次调用吗?

图例123

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个动作如何导致此方法被调用一次,但设置计时器则将其调用两次?

标记物

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章