无法更新子组件中的道具

时间:2020-10-04 04:00:10

标签: reactjs handler

这是我的父组件,具有状态(value和item)。我试图将值状态作为对子组件的支持。当我单击按钮时,在render方法中执行的代码是“执行切换”。但是,当我在componentDidMount内调用列表函数时,Toggle无法正常工作,但会执行click事件。

import React, { Component } from 'react'
import Card from './Components/Card/Card'

export class App extends Component {
  
  state = {
    values : new Array(4).fill(false),
    item : [],
  }

  toggleHandler = (index) => {
    console.log("CLICKED");
    let stateObject = this.state.values;
    stateObject.splice(index,1,!this.state.values[index]);
    this.setState({ values: stateObject });
  }

  list = () => {
    const listItem = this.state.values.map((data, index) => {
      return <Card key = {index} 
        show = {this.state.values[index]} 
        toggleHandler = {() => this.toggleHandler(index)} />
    })
    this.setState({ item : listItem  });
  }

  componentDidMount(){
    // if this is not executed as the JSX is render method is executed everything is working fine. as props are getting update in child component.
    this.list();
  }

  render() {
    
    return (
      <div>
      {/* {this.state.values.map((data, index) => {
        return <Card key = {index} 
          show = {this.state.values[index]} 
          toggleHandler = {() => this.toggleHandler(index)} />
      })
      } */}

      {this.state.item}

      </div>
    )
  }
}

export default App

这是我的子组件,状态作为道具被传递

import React from 'react'

const Card = (props) => {
    return (
        <div>
            <section>
                <h1>Name : John Doe</h1>
                <h3>Age : 20 </h3>
            </section>
            
            {props.show ?
                <section>Skills : good at nothing</section> : null
            }
            <button onClick={props.toggleHandler} >Toggle</button>
        </div>
    )
}

export default Card

我知道componentDidMount仅执行一次。但是除了直接在render方法中编写JSX之外,如何使其工作

2 个答案:

答案 0 :(得分:1)

复制状态,而不是直接对其进行变异。通过使用[... this.state.values]或this.state.values.slice()

  toggleHandler = (index) => {
    console.log("CLICKED");
    let stateObject = [...this.state.values]
    stateObject = stateObject.filter((_, i) => i !== index);
    this.setState({ values: stateObject });
  }

同样在您的render方法中,this.state.item是一个数组,因此您需要对其进行循环

  {this.state.item.map(Element => <Element />}

也可以直接在您的“渲染”方法中进行

{this.state.values.map((data, index) => {
      return <Card key = {index} 
        show = {this.state.values[index]} 
        toggleHandler = {() => this.toggleHandler(index)} />
    })}

在您的卡片组件中尝试使用

<button onClick={() => props.toggleHandler()}} >Toggle</button>

答案 1 :(得分:0)

值应该在类组件的render()内部进行映射

像这样:

 render() {
    const { values } = this.state;
    return (
      <div>
        {values.map((data, index) => {
          return (
            <Card
              key={index}
              show={values[index]}
              toggleHandler={() => this.toggleHandler(index)}
            />
          );
        })}
      </div>
    );
  }

检查沙箱以进行演示

https://codesandbox.io/s/stupefied-spence-67p4f?file=/src/App.js