从componentDidMount调度动作

时间:2020-07-02 12:17:25

标签: reactjs redux react-redux action reducers

我必须在组件安装到react.i之后立即获取一些数据。我正在使用componentDidMount方法,并且在其中我想调度一个动作,但是当我调用 popular()时(请参见代码)它什么都不做,如果我执行 dispatch(popular()),它会显示错误,即调度和种群未定义 请注意,我还没有使用mapDispatchtoProps 。我该怎么办才能获取数据?任何帮助将不胜感激。

/action.js

spring:
  jackson:
    mapper:
      infer-property-mutators: false

/App.js

export function popular(){
    return dispatch=>{
        return fetch(`https://api.themoviedb.org/3/movie/popular?api_key=<key>&language=en-US&page=1`)
                .then(data=>data.json())
                .then(data=>{
                        console.log("fetched",data);
                        dispatch({
                        type:"popular",
                        data:data.results,
                        page:data.page,
                        total_pages:data.total_pages,
                        total_results:data.total_results
                        })
     
                    })
    }
}

1 个答案:

答案 0 :(得分:1)

要调度popular操作,您需要向Redux提供redux-thunk中间件,并通过popular传递mapDispatchToProps操作。

这里有个例子:

componentDidMount() {
  this.props.getPopular();           
}

....

function mapDispatchToProps(dispatch) {
 return { getPopular: () => dispatch(popular()) };
}

thunk docs中了解有关此内容的更多信息。 另外,我建议您刷新basics of redux。只是因为您有些困惑。命名和用法告诉我有关这一点。