Dispatching actions before rendering component

时间:2016-10-20 18:59:32

标签: ecmascript-6 redux react-redux

I'm using redux and es6. I want to dispatch an action before components will mount. The problem is that with redux newest syntaxis componentWillMount doesn't exists any more. So... where should i dispatch this action.

My case: I have a component that needs user's info (such as name, for example). I need to get the user's name before that component mounts.

thanks,

1 个答案:

答案 0 :(得分:1)

将您的组件连接到您所在州的某个字段,然后将其命名为" name"。当组件呈现时,请确保它检查名称是否为空;如果它然后它呈现它,如果没有那么它什么都不呈现。

在componentDidMount中,正常触发您的调度 - 这反过来会减少并最终更改" name"在你的州。这将导致重新渲染,然后将正确显示。

componentWillMount只存在服务器端,因此通常不是最好的方法从它发送动作,就好像你只有你的客户端代码一样,它们不会工作。