获取调度函数返回值

时间:2018-01-17 06:20:18

标签: reactjs react-redux redux-thunk

我有新的反应。我试图分离组件和动作功能。但是我无法从单独的动作函数中获得返回值。是否可以从调度函数

返回一个值(例如Object {})

我把简短的代码如下:

LoginComponent.js

export function doLogin(state){
   return dispatch => {
      return axios.post('login', state).then(res =>{

      return "Some response";

    })
   }
}

LoginAction.js

{{1}}

但它没有返回任何值

三江源。

3 个答案:

答案 0 :(得分:4)

与上面的答案相反,你实际上可以从thunk返回任何你想要的东西。 Redux-thunk将通过它。

在您的情况下,您的thunk返回Promise<string>,这意味着您的组件this.props.doLogin(this.state)也会评估为Promise<string>

因此,不要尝试记录Promise,而是尝试将日志代码切换为this.props.doLogin(this.state).then(result => console.log(result);

答案 1 :(得分:1)

使用redux-thunk时,不能选择返回该函数。它将运行回调并调度您作为操作对象传递的任何内容。 因此,当您想要进行api调用时,请查看它是成功还是失败。您需要在成功时发送和采取行动。将它保存在redux状态。并访问组件中的数据

export function doLogin(state){
   return dispatch => {
      axios.post('login', state).then(res =>{
       dispatch({
        data:  "Some response",
        type: "API_SUCCESS"
       })
       })
       .catch(err) {
       dispatch({
        data:  err,
        type: "API_FAILURE"
       })
       }
}

然后像这样访问组件中的这些值

mapStateToProps = (state) => ({
data: state.yourreducer.data,
})
define mapDispatchToProps if you need dispatcch binded functions
export default(mapStateToProps, mapDispatchToProps)(YourComponent)

答案 2 :(得分:1)

您可以使用回调函数

this.props.doLogin((this.state),(result)=>{
  console.log(result)
})

export function doLogin(state,callback){
   return dispatch => {
      return axios.post('login', state).then(res =>{

      callback(res);

    })
   }
}