我可以通过其render
方法在React类中传递所有道具。
但是,如果我尝试在componentDidMount()
或什至在constructor()
中做同样的事情,那就没有运气了。
调试时,我可以在
中看到道具componentDidMount(){
const { users } = this.props <-props are already there
console.log('users from did mount', users); <-- undefined here
}
,users
变量中什么也没有出现。
当以render()
方法触发相同代码时,一切正常。
upd:完整班级
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>
)
}
}
用户是firebase对象,来自上方的父级
{ id1: {...}, id2: {...} }
答案 0 :(得分:2)
如果componentWillReceiveProps
道具来自异步,则需要使用users
方法
componentWillReceiveProps(nextProps){
if(this.props.users !== nextProps.users){
console.log('should appear here', nextProps.users);
}
}