繁体   English   中英

添加的 React 子组件没有收到更新的值

[英]Added React child component doesn't receive updated value

我正在尝试通过按钮将孩子添加到我的反应应用程序中,并通过单击按钮更新其值。 当我单击按钮时,“硬编码”子级得到更新,但通过按钮添加的子级没有被更新。 我缺少一些基本的东西。

我尝试将道具传递给孩子,假设 state 更新会传播但它不起作用。 https://codepen.io/esoteric43/pen/YzLqQOb


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

    this.state = {
      text: "Starting",
      children: []
    };
  }

  handleClick() {
    this.setState({ text: "Boom" });
  }

  handleAdd() {
    this.setState({
      children: this.state.children.concat(
        <Child1 key={1} text={this.state.text}></Child1>
      )
    });
  }

  render() {
    return (
      <div>
        <Child1 text={this.state.text}></Child1>

        {this.state.children}

        <button onClick={() => this.handleClick()}>Change</button>

        <button onClick={() => this.handleAdd()}>Add</button>
      </div>
    );
  }
}

class Child1 extends React.Component {
  render() {
    return <div>{this.props.text}</div>;
  }
}


const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <App />
);

要在上面的 codepen 链接中重现,请单击添加,然后单击更改。 添加的元素不会更新。 单击更改按钮时,应更新两个子项。

您还必须在handleClick方法中使用map之前的 state 值:

handleClick() {
    this.setState((prevState) => ({
      ...prevState,
      children:
        prevState.children.length > 1
          ? [
              ...prevState.children
                .slice(0, prevState.children.length - 1)
                .map((_) => "Boom"),
              "Boom"
            ]
          : ["Boom"]
    }));
  }

检查它在这个CodeSandbox上的工作。

您需要更新children中的最后一项。 您当前的解决方案会更新初始text

试试这样:

 class App extends React.Component { constructor(props) { super(props); this.state = { text: "Starting", children: ["Starting"] }; } handleClick() { this.setState((prevState) => ({...prevState, children: prevState.children.length > 1? [...prevState.children.slice(0, prevState.children.length - 1), "Boom" ]: ["Boom"] })); } handleAdd() { this.setState({ children: this.state.children.concat( <Child1 key={1} text={this.state.text}></Child1> ) }); } render() { return ( <div> {this.state.children.map((child, index) => ( <div key={index}>{child}</div> ))} <button onClick={() => this.handleClick()}>Change</button> <button onClick={() => this.handleAdd()}>Add</button> </div> ); } } class Child1 extends React.Component { render() { return <div>{this.props.text}</div>; } } ReactDOM.render(<App />, document.querySelector('.react'));
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>

你的意思是这样的吗?

 class App extends React.Component { constructor() { super() this.state = { children: [] } } handleAddClick = ()=>{ this.setState(prev=>({children:[...prev.children, `child ${this.state.children.length+1}`]})) } handleChangeClick=(item)=> { let draft = [...this.state.children]; draft[draft.findIndex(i=>i===item)]='boom'; this.setState({children: draft}); } render() { return( <div> <button onClick={this.handleAddClick}>Add child</button> { this.state.children.map(child=>(<Child onChange={this.handleChangeClick} title={child}/>)) } </div> ) } } class Child extends React.Component { render() { return <div> {this.props.title} <button onClick={()=>this.props.onChange(this.props.title)}>change me</button> </div> } } ReactDOM.render( <App />, document.getElementById("root") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"/>

暂无
暂无

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

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