简体   繁体   English

state中如何使用setState拼接成数组?

[英]How to use setState to splice into an array in the state?

My state.events is in array that is made up of the component instance: EventContainer.我的 state.events 在由组件实例组成的数组中:EventContainer。

I want my setState to place a new EventContainer in the state.events array.我希望我的 setState 在 state.events 数组中放置一个新的 EventContainer。 However, I want that EventContainer to go in the index immediately after the specific EventContainer that made the setState call.但是,我希望 EventContainer 到 go 的索引中紧跟在进行 setState 调用的特定 EventContainer 之后。

I'm looking for help with making the adjustments necessary to my approach or, if my entire approach is bad, a recommendation on how to go about this.我正在寻求对我的方法进行必要调整的帮助,或者,如果我的整个方法不好,我正在寻求关于如何 go 的建议。 Thank you very much.非常感谢。

I'm developing an itinerary builder which is made up of rows/EventContainers that represent an activity on a given day.我正在开发一个行程构建器,它由代表给定日期的活动的行/事件容器组成。

Each EventContainer has a button that needs to offer the user the ability to onClick an additional row immediately after that EventContainer.每个 EventContainer 都有一个按钮,需要让用户能够在该 EventContainer 之后立即添加一行 onClick。

class DayContainer extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      events: [],

    };

    this.pushNewEventContainerToState = this.pushNewEventContainerToState.bind(this);
  }




    pushNewEventContainerToState (index){
       let newEvent = <EventContainer />;
       this.setState(prevState => {
         const events = prevState.events.map((item, j) => {
           if (j === index) {
             events: [...prevState.events.splice(index, 0, newEvent)]
            }
          })
        })
      }




  render(){
    return (
        <>
          <div>
              <ul>
                  {
                    this.state.events === null
                    ? <EventContainer pushNewEventContainerToState= . 
 {this.pushNewEventContainerToState} />
                    : <NewEventButton pushNewEventContainerToState={this.pushNewEventContainerToState} />
                  }




                  {this.state.events.map((item, index) => (
                    <li
                        key={item}
                        onClick={() => 
 this.pushNewEventContainerToState(index)}
                    >{item}</li>
                  ))}

              </ul>

        </div>
      </>
    )
  }
}

My goal in setState was to splice newEvent into this.state.events immediately after the index (the parameter in pushNewEventContainerToState function).我在 setState 中的目标是在索引之后立即将 newEvent 拼接到 this.state.events 中(pushNewEventContainerToState 函数中的参数)。

I'm getting this error but I'm guessing there's more going on than just this: Line 23:22: Expected an assignment or function call and instead saw an expression no-unused-expressions.我收到了这个错误,但我猜还有比这更多的事情发生:第 23:22 行:预期分配或 function 调用,而是看到一个表达式 no-unused-expressions。

I can see at least 2 issues with the code.我可以看到代码至少有 2 个问题。 - Splice will mutate the array in place - You are not returning the updated state. - Splice 将在原地改变数组 - 您不会返回更新的 state。

You can instead use slice to build the new array.您可以改为使用slice来构建新数组。

 pushNewEventContainerToState(index) { let newEvent = < EventContainer / >; this.setState(prevState => { const updatedEvents = [...prevState.events.slice(0, index], newEvent, ...prevState.events.slice(index + 1]; return { events: updatedEvents }) }) }

As I'm fairly new to coding, it took me awhile but I was able to compile the full answer.由于我对编码还很陌生,所以我花了一些时间,但我能够编译出完整的答案。 Here is the code, below.这是代码,如下。 Below that, I explain, point by point, what the problem was and how the updated code addresses that.在此之下,我将逐点解释问题所在以及更新后的代码如何解决该问题。

class DayContainer extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      events: [{key:0}],

    };

    this.pushNewEventContainerToState = this.pushNewEventContainerToState.bind(this);
  }


      pushNewEventContainerToState(index) {
        let newEvent = {key: this.state.events.length};

        this.setState(prevState => {
          let updatedEvents = [...prevState.events.slice(0, index + 1), newEvent, ...prevState.events.slice(index + 1)];

            return {
              events: updatedEvents
            };
          })
        }

  render(){
    return (
        <>
          <div>
              <ul>
                  {this.state.events.map((item, index) => (
                    <li key={item.key}>
                        < EventContainer pushNewEventContainerToState={() => this.pushNewEventContainerToState(index) } / >
                    </li>
                  ))}

              </ul>
          </div>
        </>
    )
  }
}

Setup设置

  1. Starting with state.events , instead of starting with an empty array, I'm starting with one object , including a key starting at 0, because I always want the user to start with one EventContainer.从 state.events 开始,而不是从一个空数组开始,我从一个object开始,包括一个从 0 开始的键,因为我总是希望用户从一个 EventContainer 开始。

  2. Regarding pushNewEventContainerToState , @Sushanth made a great recommendation.关于 pushNewEventContainerToState ,@Sushanth 提出了很好的建议。 Please refer directly to that function in my latest code.请直接参考我最新代码中的function。 The refinement I made has to do with the way I separate the EventContainer being passed to this.state.events.我所做的改进与我分离传递给 this.state.events 的 EventContainer 的方式有关。 I've moved the EventContainer from pushNewEventContainerToState down to the render() element.我已将 EventContainer 从 pushNewEventContainerToState 移至 render() 元素。 I've given it a prop of key={item.key} and wrapped the component instance in a li.我给了它一个 key={item.key} 的 prop 并将组件实例包装在一个 li 中。 The very first EventContainer will have a key of 0 (see state.events[0]).第一个 EventContainer 的键值为 0(参见 state.events[0])。 Now, each new EventContainer passed to state.events will have a key that's based off the latest.length() of the state.events array (refer to the latest value of the let newEvent variable in pushNewEventContainerToState).现在,传递给 state.events 的每个新 EventContainer 都将具有一个基于 state.events 数组的 latest.length() 的键(请参阅 pushNewEventContainerToState 中 let newEvent 变量的最新值)。

All of that allowed me to fix a big problem I was facing: I needed the newest EventContainer to be placed in the index immediately after the index of the EventContainer calling pushNewEventContainerToState .所有这些让我解决了我面临的一个大问题:我需要在调用 pushNewEventContainerToState 的 EventContainer 的索引之后立即将最新的 EventContainer 放入索引中 The main reason this was happening was because I wasn't properly passing the index to the EventContainer inside of render().发生这种情况的主要原因是我没有正确地将索引传递给 render() 内部的 EventContainer。 Now that I have the actual EventContainer there, I can pass it a prop in the right manner (please refer EventContainer's prop in render).现在我已经有了实际的 EventContainer,我可以以正确的方式向它传递一个道具(请参阅渲染中的 EventContainer 的道具)。 Now I'm calling pushNewEventContainerToState with the correct index.现在我用正确的索引调用 pushNewEventContainerToState。

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

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