在调度过程之后和渲染之前调用生命周期中的哪个方法

时间:2017-08-13 08:29:57

标签: reactjs react-native react-redux reactjs-flux dispatch-async

我有一个指定哪个组件呈现的状态(组件A或B)。 我的操作调度特定类型(例如GO_TO_B或GO_TO_A)时确定此状态。

然后我需要从服务器获取一些配置来呈现组件A.我希望这些配置在store.So我应该调用一个动作(例如fetchConfig())来从服务器和调度响应中异步获取数据。

我的问题是我在哪里调用fetchConfig()动作。

如果我在组件A的componentDidMount()中调用此操作,则会发生无法在调度中间调度的错误。

那么在调度过程之后和渲染之前的反应生命周期调用中的哪个方法?

2 个答案:

答案 0 :(得分:0)

您可以使用componentWillMount Doc

在安装发生之前立即调用

componentWillMount()。它在render()之前调用,因此在此方法中同步设置状态不会触发重新呈现。避免在此方法中引入任何副作用或订阅。

答案 1 :(得分:0)

我知道您正在使用redux 如果这是正确的,我建议您使用thunk进行提取。

redux-thunk是一个允许您调度函数的中间件(而不是像行为一样的序列化对象),这样你就可以发送一个动作,甚至可以有条件地发送它。

thunk的一个例子就是:

function loadSomeThings() {
    return dispatch => {
        fetchFirstThingAsync.then(data => { // first API call
            dispatch({ type: 'FIRST_THING_SUCESS', data }); // you can dispatch this action if you want to let reducers take care of the first API call
            return fetchSecondThingAsync(data), // another API call with the data received from the first call that returns a promise
        })
        .then(data => {
             dispatch({ type: 'SECOND_THING_SUCESS', data }); // the reducers will handle this one as its the object they are waiting for
        });
    };
}  

您可以注意到我们甚至可以链接ajax请求,我们可以在每次成功时调度(如果需要)(或失败!)。

我建议您阅读文档以更好地理解它。