父母是APP.JS,子是Dasboard.js试图将用户id从App.js传递给我的孩子,dashboard.js问题是我只能在渲染时获得道具,但是在componentDidmount上,我不能再访问它了,这怎么可能?可以解释或给我链接阅读为什么会发生这种事情,我认为如果你从父母的孩子那里传递道具就能收到它,在下面的componentDidMount示例中,这种情况只在渲染中起作用。

App.js码
class App extends Component {
constructor(props) {
super(props)
this.state = {
success:null,
results:'',
}
this.CheckLoginStatus = this.CheckLoginStatus.bind(this)
}
componentDidMount(){
this.CheckLoginStatus()
}
CheckLoginStatus(){
const token = localStorage.getItem('token');
const bearer = "Bearer"
if(token === null){
this.setState({success:false})
}
axios.get('http://127.0.0.1:8000/api/details',{
headers:{
Authorization:bearer+ ' ' +token
}
})
.then(response => {
if(response.status === 200){
this.setState({success:true,results:response.data.success})
}
}).catch(err => {
localStorage.clear()
})
}
render() {
return (
<Router>
<Switch>
<Route path="/login" exact component={Login} />
<Layout>
<Route path="/dashboard" exact render={props => (
<Dashboard {...props} status={this.state.success} results={this.state.results} />
)}
/>
</Layout>
</Switch>
</Router>
)
}
}
export default App发布于 2020-03-25 02:43:38
您应该使用componentDidUpdate生命周期,因为在首字母呈现时,result state将为空。您正在获取app.js componnetdidMount生命周期中的结果数据。
当仪表板第一次安装时,结果数据将为空。
发布于 2020-03-25 02:43:19
尝试:
componentDidMount(){
this.CheckLoginStatus()
}
CheckLoginStatus = async () => {
const token = localStorage.getItem('token');
const bearer = "Bearer"
if(token === null){
this.setState({success:false})
}
await axios.get('http://127.0.0.1:8000/api/details',{
headers:{
Authorization:bearer+ ' ' +token
}
})
.then(response => {
if(response.status === 200){
this.setState({success:true,results:response.data.success})
}
}).catch(err => {
localStorage.clear()
})
}https://stackoverflow.com/questions/60842205
复制相似问题