【问题标题】:How update array in the state and show updated array with map() in reactjs如何在状态中更新数组并在 reactjs 中使用 map() 显示更新后的数组
【发布时间】:2019-10-29 13:24:51
【问题描述】:

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


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>
        )
    }
        }

【问题讨论】:

  • 你到底想做什么,你的要求是什么?

标签: reactjs ecmascript-6


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-04
    • 2021-10-16
    • 2019-08-07
    • 2021-06-10
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    相关资源
    最近更新 更多