首页 > 解决方案 > 如何在状态中更新数组并在 reactjs 中使用 map() 显示更新后的数组

问题描述

我创建一个状态并在其中创建一个数组我成功地推入数组并映射它们,但我无法在我的视图中显示更新的数组,我如何在显示任何内容之前更新状态
我的代码是:


class App extends Component{
    constructor(){
        super()
       this.state = [
           {id:'1'  , title : ''},
           {id:'2'  , title : ''},
           {id:'3'  , title : ''}
       ]


    }

    increment = (a) =>{
        this.state.push({id : ReactDOM.findDOMNode(this.refs.id).value , title : ReactDOM.findDOMNode(this.refs.user).value})
    }




    render(){
        return(
            <div>
                 <input type="text" ref='id' placeholder='id'/>
                <input type="text" ref='user' placeholder='user'/>
                <button onClick={this.increment}>+</button>
                <ul>{ 
                    this.state.map((item , id) => 
                    <li key={id}>
                    <h1>{item.title}</h1>
                    </li>)
                        }
                </ul>
            </div>
        )
    }
        }

标签: reactjsecmascript-6

解决方案


class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: [
        { id: "1", title: "title 1" },
        { id: "2", title: "title 2" },
        { id: "3", title: " title 3" }
      ]
    };
  }

  increment = a => {
    const id = ReactDOM.findDOMNode(this.refs.id).value;
    const title = ReactDOM.findDOMNode(this.refs.user).value;
    this.setState(state => {
      state.todos.push({ id, title });
      return { todos: state.todos };
    });
  };

  render() {
    const { todos } = this.state;
    console.log(todos);
    return (
      <div>
        <input type="text" ref="id" placeholder="id" />
        <input type="text" ref="user" placeholder="user" />
        <button onClick={() => this.increment()}>+</button>
        <ul>
          {todos.map((item, id) => (
            <li key={id}>
              <h1>{item.title}</h1>
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

您必须使用将值推送到数组。

 this.setState(state => {
      state.todos.push({ id, title });
      return { todos: state.todos };
    });

您可以在此处查看工作示例https://codesandbox.io/s/prod-wood-jj8rd


推荐阅读