【问题标题】:How to Differentiate input vs button state changes in react redux如何区分 React Redux 中的输入与按钮状态变化
【发布时间】:2018-06-08 16:05:38
【问题描述】:

我有一个使用 redux 的简单登录对话框(下面仅显示该对话框以供参考)。每次用户在任一输入字段中键入字符时,都会通过 redux 触发状态更改,并且当按下按钮时也会触发状态更改。

我计划在按下按钮时直接将状态更改为“LoginPending”,当 REST 调用返回时,状态将更改为“LoggedIn”或“LoginFailed”。

我目前的计划是在 MapStateToProps 方法中添加一条 if 语句,检查旧的 LoginPending 状态是否已更改,如果已更改,则发送正确的操作(实际上我将执行 toast 通知消息)。

我的问题是,“这是检查“登录”之类的正确方法吗?在 MapStateToProps 中执行此操作似乎很尴尬,但由于发生了如此多的状态更改(因为输入元素中的 onchange),我想不出更好的地方来执行此操作。

class App extends Component {
  ....
  render() {
    return (
      <div className="App">
          <input onChange={this.handleChange('username')}/><br/>
          <input onChange={this.handleChange('password')}/><br/><br/>
          <button onClick={this.handleClick}>Login</button>
      </div>
    );
  }
}

【问题讨论】:

    标签: reactjs react-redux react-redux-form


    【解决方案1】:

    有几种方法可以做到这一点。最流行的方法之一是使用redux-thunkdocsexample / official recommendation

    那么所有的逻辑都将驻留在动作创建者身上:

    export const exampleAction = (username, password) => (dispatch, getState) => {
        dispatch({type: "exampleLoading"}); // the store sets a state variable so the view can render something while this "loading" state is true
        doApiCall(username,password).then(response => {
            // here the feedback message is added on the store, so my feedback manager can render the new feedback message 
            dispatch({type: "addFeedback", payload:{message:"success!", type:"success"}});
            // here the store cleans up the "loading" variable and uses the api response if needed
            dispatch({type: "exampleLoaded", payload: response}); 
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 2023-03-14
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多