简体   繁体   English

React Js:从对象数组中更新一项

[英]React Js: update one item from array of object

in my database i have opening Time table where i have shifts of each day in the week, when i try to modify the opening time of one day ,opening Time of others day they are deleted在我的数据库中,我有打开时间表,我在一周中每天都有班次,当我尝试修改一天的开放时间时,其他一天的开放时间它们被删除


this my code to update my state data这是我的代码来更新我的状态数据

 async handleChange(e) {
    const target = e.target;
    const name = target.name;
    const value = target.value;


   await this.setState({
      opening_time: {
        ...this.state.opening_time,

        [this.state.day]: [['1', name == '0' ? value : this.state.opening_time[this.state.day][0][1], name == '1' ? value : this.state.opening_time[this.state.day][0][2]],(name == '2' || name == '3')? ['1', name == '2' ? value : this.state.opening_time[this.state.day][1][1], name == '3' ? value : this.state.opening_time[this.state.day][1][2]]:['0']]


      }
    });

    this.props.setData({ opening_time: JSON.stringify(this.state.opening_time) })



  }
  setData(data) {
    this.setState({ data: { ...this.state.data, ...data } })

  async send() {
    console.log(this.state.data)
    await callApi('post/' + this.state.id, this.state.data, 'PUT') .then(res=>{console.log(res,"yrt")
    }).catch(error=>{ this.setState({visible: "echec"})})



  }

this is my opening Time format这是我的开场时间格式

{"Mon":[["1", "08:00", "12:15"],["1", "14:14", "23:23"]],"Tue":[["0"],["0"]],"Wed":[["0"],["0"]],"Thu":[["0"],["0"]],"Fri":[["0"],["0"]],"Sat":[["0"],["0"]],"Sun":[["0"],["0"]]}

can somebody help me !有人可以帮我吗! thanks谢谢

Use the previous state to update state instead directly using this.state inside the state.使用之前的状态来更新状态,而不是直接在状态内部使用 this.state。 refer React documentation State Updates May Be Asynchronous参考 React 文档状态更新可能是异步的

in your code, you can rewrite the code like below在你的代码中,你可以像下面这样重写代码

this.setState(prevState => ({
      opening_time: {
        ...prevState.opening_time,

        [prevState.day]: [['1', name == '0' ? value : prevState.opening_time[prevState.day][0][1], name == '1' ? value : prevState.opening_time[prevState.day][0][2]],(name == '2' || name == '3')? ['1', name == '2' ? value : prevState.opening_time[prevState.day][1][1], name == '3' ? value : prevState.opening_time[prevState.day][1][2]]:['0']]


      }
    }));
 setData(data) {
    this.setState(prevState => ({ data: { ...prevState.data, ...data } })_

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

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