错误(无法读取未定义的属性(读取状态))在render()中添加this.state.a

问题描述 投票:0回答:1

我不明白为什么会出现这个错误,我从来没有使用过类组件,但我在功能组件方面有很多经验,我使用 create React app 安装了应用程序,也许我缺少一些 npm 包Es5

import React from "react";

import Tovars from './tovar'

export default class Tovar extends React.Component{
    constructor(props){
        super(props)
        this.state={
            a:true
        }
    }
    render() { 
        return (
            <>
            {this.state.a}
            </>
        )     
    }
}
javascript reactjs class npm ecmascript-5
1个回答
0
投票

您需要将

a
的值转换为字符串,因为
boolean value
不是有效的 React 子级。例如,您想要 word “true”,而不是 value
true

你的渲染方法应该如下所示:

 render() { 
        return (
            <>
            {this.state.a.toString()}
            </>
        )     
    }
© www.soinside.com 2019 - 2024. All rights reserved.