ComponentDidMount并调度一个动作

时间:2017-05-21 18:01:47

标签: reactjs react-redux

我有一个React组件,当用户点击ReactRouter链接时会加载,例如http://mysite/page/:id

在ComponentDidMount方法中,我使用以下两个操作:

postsSetPage(页)

should be a SYNC action that changes the page right away in the store). 
I'm passing it the id given from ReactRouter as page.

postsFetch(args)

is an ASYNC action that fetches data from API.

所以我的代码看起来像这样:

componentDidMount() {
    this.props.postsSetPage(this.props.match.params.id);
    console.log(this.props.posts.query); // <========== this will not be updated
    this.props.postsFetch(this.props.posts.query);
}

this.props.posts.query包含在我的API上应用过滤器/排序/分页的所有参数。它看起来像这样:

this.props.posts == {
    records: [],
    query: {
        page: 1,
        arg1: "asdasd",
        argN: "blabla",
    },
}

问题: componentDidMount中的代码不起作用,因为在我设置页面this.props.posts.query尚未更新(console.log正在确认)之后,当我调用fetch action查询时,查询不包含正确的内容页。

所以没有像setPage这样的动作假设是同步吗?

非常感谢所有帮助!

2 个答案:

答案 0 :(得分:1)

setPage作为redux操作是同步的,但由于redux存储的更改而导致的结果setState可能不是(假设setState永远不会同步)。< / p>

如果您的setPage操作通过中间件执行某些异步操作(从api获取数据)然后转发操作,那么操作本身不会导致setState同步调用,因为只有在api数据恢复后,redux store才会改变。

但我猜你正面临第一个问题。

解决问题的一种方法是在动作(thunked)中进行提取,或者在中间件中进行提取。

答案 1 :(得分:0)

根据React,this.props是不可变对象意味着您无法以编程方式更新它。 在这里你必须使用this.state

相关问题