简体   繁体   English

如何使用 array.push() 方法,以便将数据从一个组件推送到单独文件中的数组中?

[英]How do I can I use the array.push() method, so I can push data from one component into an array in a seperate file?

I have a component (Task.jsx) that recieves text data from the user, and that data needs to be pushed into an array, which is in it's own file (TaskData.js).我有一个组件(Task.jsx),它从用户那里接收文本数据,并且需要将数据推送到一个数组中,该数组位于它自己的文件(TaskData.js)中。 How do I get get the input text pushed into the array?如何将输入文本推送到数组中? Not sure how to get the two files to talk to each other.不知道如何让这两个文件相互交谈。 Code as follows:代码如下:

TaskData.js任务数据.js

const TaskData = [
    {
        id:8,
        chore: 'wash dishes'
    },
    {
        id:9,
        chore: 'do laundry'
    },
    {
        id:10,
        chore: 'clean bathroom'
    }

]

export default TaskData

Tasks.jsx任务.jsx

import React from 'react'
import TaskData from './TaskData.js'


class Tasks extends React.Component  {
    constructor(props) {
        super(props)
        this.state = {
            updatedTask: '',
            isEditing: false
        }
        this.handleClick = this.handleClick.bind(this)
        this.handleChange = this.handleChange.bind(this)
    }

handleClick () {
    TaskData.push({id:50, chore: 'test'})
        this.setState({
            isEditing:true
        })
      }

handleChange (e) {
    this.setState({
        updatedTask: e.target.value
    })
}



    render() {
    return (
        <div className = 'tasks-container'>
            <div>
                {
                this.state.isEditing ?
                <input onChange = {this.handleChange} className = 'input' placeholder ={this.props.task}/>
                : <h1 className = 'font'>{this.props.task}</h1>  
                }
        <button onClick = {this.handleClick} className ='task-button'>Edit</button> 
            </div>
        </div>
    )
    }
    
}

export default Tasks

Since react runs in the browser, you cannot write data into file.由于 react 在浏览器中运行,因此您无法将数据写入文件。 (You can read files though). (虽然您可以读取文件)。

Note that in your handleClick when you do TaskData.push(...) you have mutated the array and you will have the updated data in the memory until you refresh the page.请注意,在您的handleClick中,当您执行TaskData.push(...)时,您已经改变了数组,并且您将在memory中拥有更新的数据,直到您刷新页面。 So you can use the TaskData variable access the updated data.因此,您可以使用TaskData变量访问更新的数据。

If you specifically want to write data to file, you can store it in localStorage or you can save file on the server .如果您特别想将数据写入文件,可以将其存储在 localStorage 中,也可以将文件保存在服务器上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM