RubyLouvre / anu

the React16-compat library with hooks

Home Page:https://rubylouvre.github.io/anu/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

删除数组的第一个元素之后后续的元素setState无效

Shinhwe opened this issue · comments

问题描述:

有一个数组, 删除掉数组的第一个元素, 会导致后续数组的setState无效

具体问题代码

class P extends React.Component {
  state = {
    list: [{ id: 1, label: 'item1' }, { id: 2, label: 'item2' }]
  };

  handleClick(index) {
    if (this.state.list.length > 1) {

      this.setState({ list: this.state.list.filter((item,i) => i !== index) });
    }
  }

  render() {
    return (
      <div class="page">
        {this.state.list.map(function(item, index) {
          return (
            <div key={item.id}>
              <Welcome />
            </div>
          );
        })}
        <span onClick={this.handleClick.bind(this, 0)}>
          点我删除数组第一项元素
        </span>
      </div>
    );
  }
}

welcome.js

state = {
    text: 'nanachi'
  };

  onClick() {
    console.log('click 事件触发了,但是文本没变化')
    this.setState({
      text: '112233'
    });
  }

  render() {
    return (
      <h2 class="welcome-text" onClick={this.onClick.bind(this)}>
        Hello, {this.state.text}.
      </h2>
    );
  }

截图:

image

//index.js
import React from '@react';
import Welcome from '@components/Welcome/index';
import './index.scss';
class P extends React.Component {
    state = {
      list: [{ id: 1, label: 'item1' },
       { id: 2, label: 'item2' },
       { id: 3, label: 'item3' },
       { id: 4, label: 'item4' }
     ]
    };
  
    handleClick(index) {
        console.log(this.state.list.length, index)
      if (this.state.list.length > 1) {
          var array = this.state.list.filter((item,i) => i !== index)
          

        console.log(array.concat())
        this.setState({ list: array });
      }
    }
  
    render() {
      return (
        <div class="page">
          {this.state.list.map(function(item, index) {
            return (
              <div>
                <Welcome />
              </div>
            );
          })}
          <div onClick={this.handleClick.bind(this, 0)}>
            点我删除数组第一项元素
          </div>
        </div>
      );
    }
  }

export default P;

index.scss

page{
    height: 100%;
}
.page{
    background-color: #00afc7;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: fixed;
    height: 100%;
    width: 100%;
}
import React from '@react';
class Welcome extends React.Component{
    state = {
        text: 'nanachi'
      };
    
      onClick() {
        console.log('click 事件触发了,但是文本没变化')
        this.setState({
          text: '112233'
        });
      }
     componentWillUnmount(){
          console.log('unmout', this.props)
      }
      render() {
        return (
          <h2 class="welcome-text" onClick={this.onClick.bind(this)}>
            Hello, {this.state.text}.
          </h2>
        );
      }
}
export default Welcome

key的问题