ReactJS - 推入JSON状态数组 [英] ReactJS - push json into state array

查看:1372
本文介绍了ReactJS - 推入JSON状态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想追加一个 JSON 动态创建成阵列的<$ C里面住$ C>状态。
我发现到现在的唯一方法是使用CONCAT,因为推不工作。

I'm simply trying to append a json created dynamically into an array that lives inside the state. The only way that I've found till now is to use concat, because push doesn't work.

    constructor() {
        super()
        this.state = {
            list: []
        }
        this.add = this.add.bind(this)
    }

    add(e) {
        e.preventDefault()
        var task = document.getElementById('task').value
        var json = JSON.parse(JSON.stringify({key: task, item: task}))
        this.setState({list: this.state.list.concat(json)}) // WORKS
        // this.setState({list: this.state.list.push(json)}) // DOESN'T WORK

        console.log(this.state.list)
        document.getElementById('task').value = ''

    }

这工作,但我不明白我为什么它创造了第一个项目后,在控制台一个空数组。我读过如何CONCAT的作品,但显然我错过了一些东西。为什么我无法将this.list阵列内推对象?

That works, but I don't understand why I have an empty array in console after the first item it's created. I've read how concat works, but obviously I missed something. Why I can't push an object inside my this.list array?

推荐答案

CONCAT 否则创建一个新阵列并返回。

回报阵列,这意味着一个数字,这意味着新的长度不会您要设置为<$ C什么$ C> state.list 。这就是为什么它没有工作。

The push returns the new length of the array, which means a number, which means NOT what you want to set to state.list. That's why it didn't work.

为什么我在控制台一个空数组

why I have an empty array in console

从文档 的setState()不会立即发生变异 this.state 而造成挂起状态过渡。访问 this.state 调用此方法后可以潜在地返回现有值。这就是为什么你越来越在控制台的空数组。

From the docs: setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. That's why you are getting the empty array in the console.

还有一件事,不要直接发生变异的状态。如果你调用 state.list.push(...),您的更改将不会受到反应,如果您的通话将被丢弃的setState <维护/ code>之后。所以这是一件好事,使用 CONCAT

And one more thing, don't mutate your state directly. If you call state.list.push(...), your changes will not be maintained by React and will be discarded if you call setState later. So it's a good thing to use concat.

这篇关于ReactJS - 推入JSON状态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆