首页 > 解决方案 > 将组件作为 React setState 值传递时有问题吗?

问题描述

我对这段代码感到困惑,因为我从来没有这样写过。

所以!它有什么问题吗?我不确定。

import React from "react"
import ChildComponent from "./ChildComponent"

class App extends React.Component {
    state = {
       component: null
    }

    componentDidMount() {
       this.setState({
          component: <ChildComponent />
       })
    }

    render() {
       return {this.state.component}
    }
}

标签: javascriptreactjs

解决方案


通常,您不想将 jsx/components 存储在状态中。您的状态应包含表示 UI 状态所需的最少数据量。

回到您的问题,如果您想让您的代码正常工作,请将 jsx 存储在您的状态中(而不是函数/类引用)。同样在您的情况下,您不需要使用花括号渲染子组件。

您的代码的工作演示在这里

代码片段

import React from "react"
import ChildComponent from "./ChildComponent"

export default class App extends React.Component {
    state = {
       component: null
    }

    componentDidMount() {
       this.setState({
          component: <ChildComponent /> //<----- like this
       })
    }

    render() {
       return this.state.component  //<----- like this
    }
}

阅读内容以获取更多信息。


推荐阅读