【问题标题】:how to fix eslint distructuring state assignment in react?如何在反应中修复 eslint 解构状态分配?
【发布时间】:2019-06-25 16:56:41
【问题描述】:
 constructor(props) {
  super(props);
  const { data, image0, image1, image2, image3, image4 } = this.props;
  this.state = {
    data : data,
    image0: image0,
    image1: image1,
    image2: image2,
    image3: image3,
    image4: image4,
  };
}

renderList = () => {
  const { data } = this.state;
  const List = data.map((item, index) => {
    return (
      <Card 
        key={index}
        data={item}
        preview={this.state[`image${index}`]}
      />
    );
  })
}
...

这是我的组件代码的一部分。 我们刚刚采用 Eslint。 此代码抛出错误“必须使用解构状态分配(反应/解构分配)”。 如何修复它们??? 我们的团队不想为代码关闭这个 eslint 规则(react/distructuring-assignment)。

【问题讨论】:

    标签: reactjs state eslint destructuring


    【解决方案1】:

    首先,用道具初始化你的状态不是一个好主意。实际上它是一个 React 反模式。你可以使用 react 生命周期方法componentWillReceiveProps 来实现。

    现在要回答您的实际问题,您可能需要像这样保存一组图像:

    constructor(props) {
        this.state = {images: []}
    }
    
    // props.images contains this array ["image0", "image1", "image2", "image3", "image4"]
    
    componentWillReceiveProps(nextProps){
      if (nextProps.images !== this.props.images) {
         this.setState({ images: nextProps.images })
      }
    }
    
    render(){
      const { data } = this.state;
      const List = data.map((item, index) => {
    
        const { images } = this.state; // destruct images property from this.state
    
        return (
          <Card 
            key={index}
            data={item}
            preview={images[index]}
          />
        );
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 2022-01-16
      • 2020-12-30
      • 1970-01-01
      • 2020-02-09
      • 2017-01-18
      • 2018-12-15
      • 2015-07-16
      • 2020-11-15
      相关资源
      最近更新 更多