网址更改时组件未更改

时间:2018-03-02 16:17:00

标签: reactjs react-router

我正在处理一个问题,我的链接组件会更改URL,但除非我手动刷新整个页面,否则我的组件不会更改。

class App extends Component {
  constructor(props){
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e){
      e.preventDefault();
      this.props.changeValue(e.target.value)
    }

  render() {
    return (
      <div >
        <Link to='/'><Header /></ Link>
        <SearchBar
          value={this.props.value}
          handleChange={this.handleChange}/>

          <Switch >

          <Route exact path='/' render= { () => <ItemListContainer
          items={this.props.items} value={this.props.value}/>} />

          <Route exact path='/:id' render= {(props)=>
             <Item id= {props.match.params.id}
             details={this.props.items[props.match.params.id]}/>} />


          </ Switch >



      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

所以我意识到我必须使用withRouter,因为渲染的组件不是Route组件的子组件。

import {withRouter} from 'react-router'

class App extends Component {
  constructor(props){
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e){
      e.preventDefault();
      this.props.changeValue(e.target.value)
    }

  render() {
    return (
      <div >
        <Link to='/'><Header /></ Link>
        <SearchBar
          value={this.props.value}
          handleChange={this.handleChange}/>

          <Switch >

          <Route exact path ='/' render= { () => <ItemListContainer
          items={this.props.items} value={this.props.value}/>} />

          <Route path='/:id' render= {(props)=>
             <Item id= {props.match.params.id}
             details={this.props.items[props.match.params.id]}/>} />


          </ Switch >



      </div>
    );
  }
}



const mapStateToProps = (state) => {
  return {
    items: state.list.items,
    value: state.searchbar.value };
};

const mapDispathToProps = (dispatch) => {
  return{
    changeValue: (data) => dispatch(actions.changeValue(data))
  }
}



export default withRouter(connect(mapStateToProps, mapDispathToProps)(App))