通过父组件的onClick更新组件状态

时间:2020-09-21 19:51:31

标签: javascript reactjs components

我在应用程序中的目标是,当单击按钮时,将动作设置为new并赋予子组件。一旦子组件接收到该值,它将显示div中的文本。 在进一步的实现中,我将添加另一个按钮,单击此按钮,它将设置动作进行编辑。子组件应自动接收该值,并根据此值返回另一个div。

let actionToPerform = "";

    function actionState(action){
       if(action === 'new'){
           actionToPerform = 'new'
       }else{
           actionToPerform = 'edit'
       }
    }

 <button onClick={() => actionState('new')}>Create new Shoppinglist</button>
 <button onClick={() => actionState('edit')}>Edit Shoppinglist</button>
 <Edit action={actionToPerform}/>

子组件:

export default class Edit extends React.Component {


    constructor(props){
        super(props);
        this.state = {actionToPerform: this.props.action}
    }

    

    showTitle() {
        if(this.state.actionToPerform === 'new'){
            return <div>new Shoppinglist</div>
        }else if(this.state.actionToPerform === 'edit'){
            return <div>edit</div>
        }else{
            return <div>nothing to show</div>
        }
    }



   render() {
       return (
           this.showTitle()
       )
   }
}

我知道我应该以某种方式使用componentDidMount和componentUpdate来完成此任务,但无法做到这一点。 现在,在加载页面时,它会触发onClick动作,我不知道为什么。当我单击按钮时,没有其他反应

2 个答案:

答案 0 :(得分:1)

父组件:

在更新actionToPerform时,您的组件不知道并且不会重新呈现,您需要将其保留在其state中:

state = {
  actionToPerform: ""
}

updateState(actionToPerform){
    this.setState({ actionToPerform })
}

<button onClick={() => this.updateState('new')}>Create new Shoppinglist</button>
<button onClick={() => this.updateState('edit')}>Edit Shoppinglist</button>
<Edit action={actionToPerform}/>

现在,当您单击其中一个按钮时,状态值会更新,并且组件会重新呈现,将新值传递给子级。

子组件:

您不应从props设置状态的初始值,请参见Anti-pattern: Unconditionally copying props to state

您甚至可以将其全部删除,因为您可以根据props值进行条件渲染:

export default class Edit extends React.Component {
  render() {
    return this.props.actionToPerform === "new" ? (
      <div>new Shoppinglist</div>
    ) : this.props.actionToPerform === "edit" ? (
      <div>edit</div>
    ) : (
      <div>nothing to show</div>
    );
  }
}

答案 1 :(得分:0)

应该使用Edit组件中的状态,而不是使用parentt组件中的状态,并将该状态作为prop传递给子(编辑)组件并使用。

parent.js

actionState = (action) => {
   if(action === 'new'){
      this.setState({ actionToPerform: 'new' })
   } else{
      this.setState({ actionToPerform: 'edit' })
   }
}
render() {
 return (
   <div>
     <button onClick={() => this.actionState('new')}>Create new Shoppinglist</button>
     <button onClick={() => this.actionState('edit')}>Edit Shoppinglist</button>
     <Edit action={this.state.actionToPerform}/>
   </div>
 )
}

child.js

export default class Edit extends React.Component {

    showTitle() {
        if(this.props.actionToPerform === 'new'){
            return <div>new Shoppinglist</div>
        } else if(this.props.actionToPerform === 'edit'){
            return <div>edit</div>
        } else{
            return <div>nothing to show</div>
        }
    }

   render() {
       return (
           this.showTitle()
       )
   }