繁体   English   中英

从搜索到结果的React Router v4重定向传递状态

[英]React Router v4 Redirect Passing State from Search to Results

具有搜索组件,当有效负载返回时,该组件将重定向到结果组件。 希望该结果组件显示使用React Router v4 Redirect传递的搜索状态。 我从文档中得出的假设是,使用state: { referrer: currentLocation }可以传递对象。

搜索

export default class Search extends Component{
  constructor(props){
    super(props);
      this.state = {
        searchValue: '',
        results:[]
      }
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }

  handleKeyPress = (e) => {
    let searchParam = e.target.value;
    if (e.key === 'Enter'){
      axios
        .get(URL+searchParam)
        .then((response) => {
          this.setState({results: response.data});
        });
    }
  };

  render(){
    return(
      <div>
        <input
          ref="search"
          type="text"
          placeholder="Search"
          onKeyPress={this.handleKeyPress.bind(this)}
        />
        {this.state.results.length > 0 &&
          <Redirect to={{
            pathname: '/results',
            state: { results: this.state.results }
          }} />
        }
      </div>
    );
  }
}

结果

export default class Results extends Component{
  constructor(props){
    super(props);
    this.state = {
      results:[] // <<<<<< Not sure if this needs set
    }
  } 
  render(){
    console.log('SEARCH RESULTS STATE', this.state); // <<<< this either returns undefined or just an empty array depending if initial state is set
    return(
      <div>
        <h1>Search Results</h1>
      </div>
    );
  }
}

除非我没有正确地读懂它,否则问题似乎是当重定向发生时,没有任何东西传递到结果组件中。

如果输入了值并且成功进行了重定向,则搜索状态将返回Object {searchValue: "", results: Array(1)}但是“搜索结果”状态将返回Object {results: Array(0)}undefined具体取决于初始状态设置。

还尝试了对结果使用不同的组件生命周期,但无法以这种方式获取任何传递的数据。 我认为可能有componentWillRecieveProps(nextProps, nextState){}可能能够获取一些传递的数据,并可以通过这些方式设置状态。

在您的主要Class Component的render()方法的开头,您必须进行编码,例如:

if (isLoggedIn){
    return <Redirect to={{
      pathname: '/anyPath',
      state: { stateName: this.state.anyState}
    }} />;
}

在与Route /anyPath关联的组件中,您必须提取传递的状态,调用this.props.location.state.stateName 在您的情况下,您应该在Results类中调用this.props.location.state.results 您可以从Results类中删除构造方法。

isLoggedIn可能是另一种状态,您可以首先从主组件的构造函数Method中将其设置为false。 然后,如果您的用户单击一个按钮,则isLoggedIn可以设置为true,因此您可以将您的应用重定向到其他具有首选状态的Route。

看起来该对象已通过,但是它嵌套在location.state并且看起来不够深。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM