gpt4 book ai didi

javascript - 除了 render 方法之外,还有什么方法可以在 React 类中获取 props 吗?

转载 作者:行者123 更新时间:2023-11-29 20:51:37 24 4
gpt4 key购买 nike

我可以在 React 类的 render 方法中获取传递给它的所有 Prop 。但是,如果我尝试在 componentDidMount() 或什至在 constructor() 中做同样的事情 - 运气不好。

调试时我可以在

中看到 Prop
componentDidMount(){
const { users } = this.props <-props are already there
console.log('users from did mount', users); <-- undefined here
}

users 变量中没有任何内容。

相同 代码在 render() 方法中触发时——一切正常。

更新:全类

import React, { Component } from 'react'
import { firebaseDB, functions } from '../firebase'
import map from 'lodash/map'

export default class Users extends Component {

state = {
users: []
}


componentDidMount(){
const { users } = this.props
console.log('users from did mount', users); // undefined here
// here I'd like to some work with those props
}

handleUser = user => () => {
// console.log('user to handle:',user); //is here
... handling user data
}

render() {
const { users } = this.props //ok
console.log('users from render', users);//see it

return (
<div className="container">

{users ?
<div>
<h4 className="text-primary">Users List</h4>
<table className="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">email</th>
<th scope="col">Something</th>
</tr>
</thead>
<tbody>
{
map(users, (user, key) => (
<tr key={key}>
<td>{user.displayName}</td>
<td>{user.email}</td>

<td><button
className="btn btn-primary"
onClick={this.handleUser(user)}
>ok</button></td>

</tr>
))
}

</tbody>
</table>
</div>
:
"There are no users yet "
}
</div>
)
}
}

users是firebase对象,来自上面的parent

{ id1: {...}, id2: {...} } 

最佳答案

你需要使用 componentWillReceiveProps 方法以防 users 属性来自异步

componentWillReceiveProps(nextProps){
if(this.props.users !== nextProps.users){
console.log('should appear here', nextProps.users);
}
}

关于javascript - 除了 render 方法之外,还有什么方法可以在 React 类中获取 props 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51563723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com