单击按钮导航到另一个路径并将道具传递给它

时间:2017-09-12 05:40:45

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

我想点击一个按钮打开一个新页面(我已经制作了路线的组件)并将一些数据传递给它。
直到现在我已经这样做了:
在我的app.js组件中,我有这个(路由):

class App extends Component {
  render() {
    return (
      <Router>
       <div>
        <Route exact path="/" component={Login} />
        <Route exact path="/dashboard" component={Dashboard} />
       </div>
      </Router>
    );
  }           

在Login组件中我有:

class Login extends Component {
  constructor(props){
    super(props);
    //this.state = {isToggleOn: true};
    this.loadDashboard = this.loadDashboard.bind(this);
    this.handleOnSubmit = this.handleOnSubmit.bind(this);
    this.setData = this.setData.bind(this);
    this.state = {values:null}
  }
  setData(data){
    this.setState({values:data});
  }
  loadDashboard(token){
    console.log(token);
    axios({                 //this function is used to fetch some data from server
      method:'get',
      url:'http://localhost:3000/api/dashboard',
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
     .then(function (response) {
       console.log(response.data);     //it works!   
       this.setData(response.data)
     })
     .catch(function (error) {
       console.log("Error in loading Dashboard "+error);
     });
  }
render() {
    return (
      <div>
         Username: <input type="email" name="fname" /><br />
         Password: <input type="password" name="lname" /><br />
         <button onClick={this.handleOnSubmit}>LOG IN</button>
         <Dashboard data={this.state.values} />
      </div>
    );
  }
} 

注意 response.data包含三个json对象的数组 直到现在我无法使用我的子组件(仪表板)打印传递的值 我的Dashboard组件如下所示:

class Dashboard extends Component {
  constructor(props){
    super(props);
      console.log(this.props.data);
  }
  render() {
    return (
      <h2>hi{this.props.data}</h2>     <!--Only hi gets printed -->
    );
  }
}

export default Dashboard;         
  • 如何点击按钮显示Dashboard组件,即将我的网址更改为/dashboard并将一些值传递给它?

0 个答案:

没有答案