获取调度函数返回值

Ang*_*ger 5 reactjs redux-thunk react-redux

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

我把简短的代码如下:

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);
Run Code Online (Sandbox Code Playgroud)

LoginAction.js

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

      return "Some response";

    })
   }
}
Run Code Online (Sandbox Code Playgroud)

但它不返回任何值

谢谢。

cas*_*ber 7

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

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

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


小智 5

您可以使用回调函数

this.props.doLogin((this.state),(result)=>{
  console.log(result)
})
Run Code Online (Sandbox Code Playgroud)

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

      callback(res);

    })
   }
}
Run Code Online (Sandbox Code Playgroud)


sim*_*lor 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"
       })
       }
}
Run Code Online (Sandbox Code Playgroud)

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

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