Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应路由器:更新路由';新道具上的s组件_Reactjs_React Router - Fatal编程技术网

Reactjs 反应路由器:更新路由';新道具上的s组件

Reactjs 反应路由器:更新路由';新道具上的s组件,reactjs,react-router,Reactjs,React Router,App.js import React,{Component}来自'React'; 从“react Router”导入{Router,Route,browserHistory}; 从“./Login”导入登录名; 从“./课程”导入课程; 类应用程序扩展组件{ 构造函数(){ 超级(); 此.state={ 用户名:“”, 密码:“” }; } setCredentials=({username,password})=>{ 这是我的国家({ 用户名, 密码 }); } render(){ 返回(

App.js

import React,{Component}来自'React';
从“react Router”导入{Router,Route,browserHistory};
从“./Login”导入登录名;
从“./课程”导入课程;
类应用程序扩展组件{
构造函数(){
超级();
此.state={
用户名:“”,
密码:“”
};
}
setCredentials=({username,password})=>{
这是我的国家({
用户名,
密码
});
}
render(){
返回(
);
}
}
Login
组件从用户处接收凭据,通过API调用验证凭据,用凭据更新
App
的状态,然后使用
this.props.router.push('/Courses')
重定向到
Courses
组件

课程
组件应将更新的凭证(即
应用程序
的更新状态)作为道具,然后执行API调用以获取该用户的课程


如何在
课程
组件中检测
应用程序
状态的更新?我完全做错了吗?

正如您所说的,使用从道具中读取的课程组件,您可以在课程组件中有一个这样的生命周期挂钩:

componentWillReceiveProps(nextProps) {
  if(nextProps.isAuthenticated && this.props.credentials !== nextProps.credentials) {
    // perform fetch for courses here
  }
}
将道具正确传递到路线的组件: 而不是:

    <Route
      path='/courses'
      component={Courses}
      credentials={this.state}
      />

答案是:

如何在Courses组件中检测应用程序状态的更新


由于
crendentials
成为
Courses
的道具,其值
state
成为
App
的道具,不幸的是
componentWillReceiveProps
从未被调用。@Abdelrahmanged新的答案将解决
componentWillReceiveProps
从未被调用的问题react router组件的属性,而不是您自己的属性。
   <Route
      path='/'
      component={(props) => <Login  setCredentials={this.setCredentials} {...props} />}
      />
   <Route
      path='/'
      component={Login}
      setCredentials={this.setCredentials}
      />
    <Route
      path='/courses'
      component={(props) => <Courses credentials={this.state} {...props} />}
      />
    <Route
      path='/courses'
      component={Courses}
      credentials={this.state}
      />