【问题标题】:Objects are not valid as a React child (found: object with keys). If you meant to render a collection of children, use an array instead对象作为 React 子对象无效(找到:带键的对象)。如果您打算渲染一组孩子,请改用数组
【发布时间】:2021-11-18 18:17:19
【问题描述】:
constructor(props) {
        super(props);
        this.state = {
            message: []
        };
    }

    async getData() {
        await axios.get("https:...")
        .then((response) => {
            console.log((response));
            console.log(typeof(response)); // object
            const convertString = JSON.parse(response.data.body);
            this.setState({message: convertString});
            console.log(convertString));
        })
    }

    componentDidMount() {
        this.getData();
    }

    render() {
        const obj = (this.state.message);
        console.log(obj);
        return(
            <div>
                {this.state.message}
            </div>
        )

我收到错误消息:“错误:对象作为 React 子项无效(找到:带有键 {Items, Count, ScannedCount} 的对象)。如果您要渲染一组子项,请改用数组。”

console.log(convertString) 给了我这个:

Items: Array(4)
0: {key1: "value", key2: "value"}
1: {key1: "value", key2: "value"}
2: {key1: "value", key2: "value"}
3: {key1: "value", key2: "value"}

如果我想以表格格式呈现数组,我应该如何通过 this.setState() 传递数据?

【问题讨论】:

    标签: arrays reactjs object children


    【解决方案1】:

    如您所见,您的响应是一个对象数组。例如,您必须通过该数组循环抛出以正确显示数据。

        render() {
          return(
            <div>
                {this.state.message.map((item,i) => (
                  <div key={i}> 
                   <div>{item.key1}</div>
                   <div>{item.key2}</div>
                  </div>
                )}
            </div>
          )
        }
    

    在 {this.state.message.map} 方法中,您在消息数组中循环抛出(包含 4 个对象),并且每个(项目)都有您要显示的属性。

    【讨论】:

    • 我收到错误:this.state.message.map 不是函数
    • 你删除了 render() 之后的两行吗?常量 obj = (this.state.message); console.log(obj);
    • 有或没有 2 行我得到同样的错误
    • 替换你的 .then 行.. 直到 console.log(convertString) 用那个..then((response) => response.json()) .then(messageList=> { this. setState({ message: messageList});
    猜你喜欢
    • 2020-10-18
    • 2019-10-12
    • 2021-04-19
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多