首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在React中将输入数据添加到JSON数组。

如何在React中将输入数据添加到JSON数组。
EN

Stack Overflow用户
提问于 2018-08-06 08:29:10
回答 1查看 3.6K关注 0票数 2

我一直致力于理解React的概念,并完成了我的Todo项目。我显示了虚拟数据,但不能向虚拟数据添加新值,虚拟数据存储在单独文件todos.js中的对象数组中。

这是file hierarchy

这是我得到的错误-

index.js:2177 Warning: Each child in an array or iterator should have a unique "key" prop.

TodoList.js

代码语言:javascript
复制
import React from 'react';
import Todo from './Todo';
import todos from '../todos'

class TodoList extends React.Component {
    constructor() {
        super();
        this.state = {
            todoItems: todos,
            newItem: {}
        }
    }

    addItem = (event) => {
        event.preventDefault();
        const todoList = this.state.todoItems;
        todoList.push(this.state.newItem);
        this.setState({ 
            todoList: todos,
            newItem: {}
        });

    };

    handleInput = (event) => {
        this.setState({ newItem: event.target.value });
    }

    render() {
        const itenary = this.state.todoItems;
        return (
            <div>
                {itenary.map(todo =>
                    <div key={todo.id}>
                        <Todo handleClick={this.props.handleClick} thing={todo} />
                    </div>

                )}
                <br />
                <form onSubmit={this.addItem}>
                    <input type="text" onChange={this.handleInput} placeholder="Add a new task" />
                    <button>Submit</button>
                </form>
            </div>
        );
    }
}

export default TodoList;

Todo.js

代码语言:javascript
复制
import React from 'react';

class Todo extends React.Component {
    constructor() {
        super();
        this.state = {
            clicked: false
        }
    }


    handleClick = () => {
        this.setState({ clicked: !this.state.clicked });
    }

    render() {
        const styles = this.state.clicked ? { textDecoration: 'line-through' } : { textDecoration: 'none' };
        return (
            {/* This is where the todo item is*/}
            <div style={styles} onClick={this.handleClick} key={this.props.thing.id}>{this.props.thing.text}</div>
        );
    }
}

export default Todo;

todos.js

代码语言:javascript
复制
const todos = [
    { id: 1, text: 'Go to the gym', 'completed': false },
    { id: 2, text:  'Do laundry', 'completed': false },
    { id: 3, text: 'Study for exams', 'completed': false },
    { id: 4, text: 'Read a book', 'completed': false },
    { id: 5, text: 'Clean the bedroom', 'completed': false },
    { id: 6, text: 'Go to the park', 'completed': false },
];

export default todos; 

任何帮助和/或反馈都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-06 08:36:48

您必须为添加到todoItems的新todo提供一个唯一的id,React可以使用该use在呈现它们时将其与其他todo区分开来。

您也不应该使用push来改变当前状态。相反,您应该使用一个全新的数组来设置state,该数组包含前一个数组所做的一切。

示例

代码语言:javascript
复制
class TodoList extends React.Component {
  constructor() {
    super();
    this.state = {
      todoItems: todos,
      newItem: ""
    };
  }

  addItem = event => {
    event.preventDefault();
    this.setState(prevState => {
      return {
        todoItems: [
          ...prevState.todoItems,
          { id: Math.random(), text: prevState.newItem, completed: false }
        ],
        newItem: ""
      };
    });
  };

  // ...
}

代码语言:javascript
复制
const todos = [
  { id: 1, text: "Go to the gym", completed: false },
  { id: 2, text: "Do laundry", completed: false },
  { id: 3, text: "Study for exams", completed: false },
  { id: 4, text: "Read a book", completed: false },
  { id: 5, text: "Clean the bedroom", completed: false },
  { id: 6, text: "Go to the park", completed: false }
];

class TodoList extends React.Component {
  constructor() {
    super();
    this.state = {
      todoItems: todos,
      newItem: ""
    };
  }

  addItem = event => {
    event.preventDefault();
    this.setState(prevState => {
      return {
        todoItems: [
          ...prevState.todoItems,
          { id: Math.random(), text: prevState.newItem, completed: false }
        ],
        newItem: ""
      };
    });
  };

  handleInput = event => {
    this.setState({ newItem: event.target.value });
  };

  render() {
    const itenary = this.state.todoItems;
    return (
      <div>
        {itenary.map(todo => (
          <div key={todo.id}>
            <Todo handleClick={this.props.handleClick} thing={todo} />
          </div>
        ))}
        <br />
        <form onSubmit={this.addItem}>
          <input
            type="text"
            onChange={this.handleInput}
            value={this.state.newItem}
            placeholder="Add a new task"
          />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

class Todo extends React.Component {
  constructor() {
    super();
    this.state = {
      clicked: false
    };
  }

  handleClick = () => {
    this.setState({ clicked: !this.state.clicked });
  };

  render() {
    const styles = this.state.clicked
      ? { textDecoration: "line-through" }
      : { textDecoration: "none" };
    return (
      <div style={styles} onClick={this.handleClick} key={this.props.thing.id}>
        {this.props.thing.text}
      </div>
    );
  }
}

ReactDOM.render(<TodoList />, document.getElementById("root"));
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51699285

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档