通过 react-redux 动作负载传递输入值?

bnh*_*bnh 0 react-redux

export class SearchBar extends React.Component {
  render() {
    return (
      <div>
        <input onChange={this.props.onSearchTermChange} />
      </div>
    );
  }
}

const mapDispatchToProps = dispatch => {
  return {
    onSearchTermChange: () =>
      dispatch({
        type: "SEARCHTERMCHANGE",
        payLoad: {}
      })
  };
};
Run Code Online (Sandbox Code Playgroud)

基本上,当输入更改时,我想调用“onSearchTermChange”操作并将输入值传递给减速器,但我不知道如何从操作 onSearchTermChange 访问输入值。

Pra*_*nna 7

你必须使用 event.target.value

<input 
  onChange={ (e) => this.props.onSearchTermChange(e.target.value)} 
  value={this.props.value} 
/>
Run Code Online (Sandbox Code Playgroud)

你的动作创建者现在

const mapDispatchToProps = dispatch => {
  return {
    onSearchTermChange: (value) =>
      dispatch({
        type: "SEARCHTERMCHANGE",
        payLoad: value
      })
  };
};
Run Code Online (Sandbox Code Playgroud)

和你的减速机

case "SEARCHTERMCHANGE":
  return {
    ...state,
    value: action.payLoad
  }
Run Code Online (Sandbox Code Playgroud)

最后,您需要将您的值导入到您的道具中。

const mapStateToProps = (state) => ({
   value: state.value,
})
Run Code Online (Sandbox Code Playgroud)