【问题标题】:Can't get this.props inside child componentDidMount无法在子 componentDidMount 中获取 this.props
【发布时间】:2019-03-30 03:14:22
【问题描述】:

在我的 app.js 中,我正在使用 firebase 进行身份验证并将用户保存在状态中并作为道具发送到 Home 组件。

export default class App extends React.Component {

    constructor(props) {
        super(props);
        this.state={
            user:{}
        }
    }

    componentDidMount() {
        this.authListener();
    }

    authListener() {
        fire.auth().onAuthStateChanged((user) => {
            if(user) {
                this.setState({user});
            } else {
                this.setState({user:null});
            }
        })
    }
    render() {
        return (
            <div className="App">
                {this.state.user ? (<Home user={this.state.user} />) : (<Login />)}
            </div>
        )
    }
}

然后在我的 Home.js 中

export default class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            registered: false
        };
    }

    componentDidMount() {
        console.log(this.props);
    }
    render() {
        return (
            <div className="container">
                <h1>Home</h1>
            </div>
        )
    }
}

console.log(this.props) 返回一个空用户:

{user: {…}}

奇怪的是,如果我只 console.log(this),我会得到整个对象,包括拥有所有信息的用户。

Home {props: {…}, context: {…}, refs: {…}, updater: {…}, state: {…}, …}
context: {}
props: {user: Lk}
refs: {}
state: {error: null, registered: false}
updater: {isMounted: ƒ, enqueueSetState: ƒ, enqueueReplaceState: ƒ, enqueueForceUpdate: ƒ}
_reactInternalFiber: FiberNode {tag: 2, key: null, type: ƒ, stateNode: Home, return: FiberNode, …}
_reactInternalInstance: {_processChildContext: ƒ}
isMounted: (...)
replaceState: (...)
__proto__: Component

为什么我无法访问 componentDidMount 中的 this.props ?

谢谢!

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这是因为 componentDidMount 最初是用一个空的 user一个空对象)调用的。您只需在身份验证检查后将其设置为null

    所以,this.state.user 最初会评估为 true,因为

    this.state={
            user:{}
        }
    

    如果您将初始状态设置为 user:null,它将起作用,因为 Home 组件仅在用户存在时才会被挂载。


    所以流程是,Home 组件挂载了一个空的 {} user,并且运行 componentDidMount 并记录了一个空的 user 属性。然后,当您进行身份验证时,组件确实运行componentDidMount,因为它已经是 mounterdit 仅使用新道具重新渲染。

    【讨论】:

      【解决方案2】:

      由于官方文档

      您可以立即在 componentDidMount() 中调用 setState()。它会 触发额外的渲染,但它会在浏览器之前发生 更新屏幕。这保证了即使 render() 将 在这种情况下被调用两次,用户不会看到中间 状态。谨慎使用此模式,因为它通常会导致 性能问题。在大多数情况下,您应该能够分配 构造函数()中的初始状态。然而,它可以是 当您需要测量时,对于模态和工具提示等情况是必需的 渲染之前的 DOM 节点,这取决于它的大小或 位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-28
        • 2019-07-30
        • 2019-06-07
        • 2019-10-28
        • 1970-01-01
        • 1970-01-01
        • 2019-04-17
        • 2016-09-03
        相关资源
        最近更新 更多