javascript - 将组件作为 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}
}
}
解决方案
通常,您不想将 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
}
}
阅读此内容以获取更多信息。
推荐阅读
- python - Python Selenium 从 tr 内的 td 使用 xpath 获取数据
- reactjs - 如何清除 React 中的输入字段?
- javascript - 如何使用 Sequelize.js 解析复杂的查询操作?
- oracle - 在 Oracle 中创建指向 Google BigQuery 的数据库链接失败并出现 ORA-28511
- python - 删除收集的静态文件
- python - seaborn pairplot不适用于单个图
- c# - 迁移不会创建数据库
- reactjs - 为 React Native 组合/嵌套/实现 Stack Navigator 和 Tab Navigator React Navigation 组件
- python - 我正在尝试在 python 的帐户页面上显示来自 Azure AD 的照片
- c - Do while 语句中的问题不断循环