【问题标题】:Getting dispatch function return value获取调度函数返回值
【发布时间】:2018-06-25 23:00:02
【问题描述】:

我是新来的反应。我试图将组件和动作功能分开。但我无法从单独的操作函数中获取返回值。是否可以从调度函数返回一个值(例如 Object {})

我把简要代码如下:

LoginComponent.js

class Login extends React.Component {
   constructor(props){
      super(props)
      this.state = {
         username : '',
         password : ''
      }
   }
   submit = (e) => {
      /* console.logging "Some response"*/
      console.log(this.props.doLogin(this.state))
   }
   render(){
      return (
         <form onSubmit={this.submit}>/* some login element */</form>
      )
   }
}

export default connect(null, {LoginAction})(Login);

LoginAction.js

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

      return "Some response";

    })
   }
}

但它不返回任何值

谢谢。

【问题讨论】:

    标签: reactjs react-redux redux-thunk


    【解决方案1】:

    与上述答案相反,您实际上可以从 thunk 中返回您想要的任何内容。 Redux-thunk 会通过它。

    在您的情况下,您的 thunk 返回 Promise&lt;string&gt;,这意味着在您的组件中 this.props.doLogin(this.state) 也将评估为 Promise&lt;string&gt;

    因此,与其尝试记录Promise,不如尝试将该记录代码切换到this.props.doLogin(this.state).then(result =&gt; console.log(result);

    【讨论】:

      【解决方案2】:

      你可以使用回调函数

      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);
      
          })
         }
      }

      【讨论】:

        【解决方案3】:

        在使用 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)
        

        【讨论】:

          猜你喜欢
          • 2014-05-28
          • 1970-01-01
          • 2011-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-24
          • 2020-01-12
          相关资源
          最近更新 更多