【问题标题】:How can I append an item to a list in js in reactjs如何在 reactjs 中将项目附加到 js 中的列表中
【发布时间】:2021-07-11 09:46:23
【问题描述】:

我创建了一个父组件 js 文件并通过向其添加 10 来更改状态 fo 数字列表,但它显示错误,因为没有推送功能。有人可以帮我解决这个问题吗??

import React, { Component,PureComponent } from 'react'
import Reg from './Regularcomp'
import Pure from './PureComp'

export class Parentcomp extends PureComponent {

constructor(props) {
    super(props)

    this.state = {
         name:"Mayank",
         numbers:[1,2,3,4,5,6]
    }
}


componentDidMount()
{
    setInterval(()=>{
            this.state.numbers = this.state.numbers.push(10)
    },1000)
}

render() {
    console.log("*****Parent Component*******")
    return (
        <div>
            Parent is Pure Component
            <Reg name={this.state.name}/>
            <Pure name={this.state.name}/>
        </div>
    )
}
}

export default Parentcomp

【问题讨论】:

  • 欢迎来到社区。请强烈考虑为您的 ❓ 添加更多上下文,而不仅仅是代码。目前您的代码格式已关闭,没有提供任何其他内容。

标签: javascript reactjs list


【解决方案1】:

React 类组件中的state 接口是一个复杂的结构。它不会在您的数据结构上为您提供任何简单的setters。您可以在其上使用的唯一设置器是 setState 方法。所以你应该将你的componentDidMount 重写为:

componentDidMount() {
    setInterval(() => {
        this.setState((prevState) => ({
            numbers: [...prevState.numbers, 10]
        }));
    }, 1000);
}

【讨论】:

  • 你的代码说Cannot read property push of undefined
  • 更新了答案。
  • 为什么数组的推送功能在这里不适用?我找不到任何原因
  • React 通过比较 references 检测对象何时更改。并且推送操作不会更改numbers 数组的引用。虽然对象内部会发生变化,但 react 不会触发重新渲染,因为引用没有改变。
  • 这是因为我使用 PureComponent 类作为父类。如果我只使用 Component 类作为我的父类,那么它应该总是重新渲染。它也不起作用。
猜你喜欢
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 2011-10-12
相关资源
最近更新 更多