【问题标题】:React-redux-router push with action/reducerReact-redux-router 使用 action/reducer 推送
【发布时间】:2017-08-31 05:33:42
【问题描述】:

我有一个简单的点击处理程序,它将一个对象(selectedPost)传递给一个动作 - 下面是组件:

class SearchBarContainer extends Component {
  render() {
    return (
        <div>
          <div className="center-xs">
            <p>To get started, type in some keywords below</p>
          </div>
          <SearchBar onTermChange={this.props.actions.loadPosts} onNull={this.props.actions.nullPosts}/>  
          <PostList posts={this.props.posts} isFetching={this.props.isFetching} onClick={this.props.actions.selectPost}/>
        </div>
    );
  }
}

下面是动作:

export function selectPost(post) {
  return {
    type: SELECT_POST,
    payload: post
  }
}

我想要做的是同时将 url 更改为 push 到 /product/foo 但我不知道我把这段代码放在哪里 - 任何帮助表示赞赏

【问题讨论】:

  • 在类里面定义一个fun并分配给onClick,在那个fun里面首先调用action然后改变路由。
  • 啊,谢谢你说得有道理,你能不能发一些我还在苦苦挣扎的示例代码
  • 检查@shubham 的回答它会解决你的问题:)

标签: reactjs react-redux react-router-v4


【解决方案1】:

您可以通过调用函数 onClick 然后更改路由以及从函数内调用操作来实现

class SearchBarContainer extends Component {
  selectPost = (post) => {
      this.props.history.push('/product/foo');
      this.props.actions.selectPost(post)
  }
  render() {
    return (
        <div>
          <div className="center-xs">
            <p>To get started, type in some keywords below</p>
          </div>
          <SearchBar onTermChange={this.props.actions.loadPosts} onNull={this.props.actions.nullPosts}/>  
          <PostList posts={this.props.posts} isFetching={this.props.isFetching} onClick={this.selectPost}/>
        </div>
    );
  }
}
export default withRouter(SearchBarContainer);

【讨论】:

  • 完美 - 非常感谢。我唯一需要做的就是将 post 对象添加到 selectPost 方法中: selectPost = (post) => { this.props.history.push('/product/foo'); this.props.actions.selectPost(post); }
  • 我喜欢这种方法,因为我只是将数据从 redux 传递到下一个组件,因此加载是即时的,而且我什至不需要网络请求的 url 参数 - 因此 /product/foo
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 2019-05-16
  • 1970-01-01
  • 2018-10-03
  • 2018-07-24
  • 1970-01-01
  • 2018-11-08
  • 2016-08-16
相关资源
最近更新 更多