代码之家  ›  专栏  ›  技术社区  ›  alopez02

如何在React中的状态更改时更新prop的值

  •  0
  • alopez02  · 技术社区  · 5 年前

    import theKeyComponent from "../components/theKeyComponent.jsx";
    
    export default class MainComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
         activeLink: '#section1'
        }
      }
      render(){
       const myId = this.state.activeLink === '#section1' ? '0001' : '0002';
       return(){
         <theKeyComponent myID={myID} />
         <otherComponent otherPropsHere={otherProps} />
       }
      }
    }
    

    这是钥匙组件内部的一点

    export default class HelpScoutBeacon extends React.Component {
      static propTypes = {
        myID: PropTypes.string.isRequired
      }
      componentDidMount() {
        myAPImethod('init', this.props.myID);
      } 
      render(){return(){}}
    }
    

    我想根据“activeLink”的值更改常量myID的值。第一次安装两个组件时,这不是问题。但是,当“activeLink”的值更改时,“myID”不会更改,因为子组件已经装入。

    我是新来的反应,所以我希望我可以得到一些澄清,所以社区。

    1 回复  |  直到 5 年前
        1
  •  1
  •   95faf8e76605e973    5 年前

    第一次安装两个组件时,这不是问题 更改,因为子组件已装入。

    componentDidMount componentDidUpdate 对生命周期作出反应 组件安装 组件更新 将在activeLink状态更改时触发,因为您将其作为道具传递给 theKeyComponent

    componentDidUpdate() {
        myAPImethod('init', this.props.myID);
    } 
    

    参考文献: https://reactjs.org/docs/react-component.html#componentdidupdate

        2
  •  0
  •   Azizul Hoq    5 年前
    import theKeyComponent from "../components/theKeyComponent.jsx";
    
    export default class MainComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
         activeLink: '#section1'
        }
      }
    
     static getDerivedStateFromProps(props, state) {
        if (props.activeLink !== state.activeLink ) {
          // updating the state here if there are any changes in props.
          return {
            activeLink: props.activeLink,
          };
        }
    
        // Return null if the props hasn't changed
        return null;
        }
    

     render(){
      // now, here your state is updated. 
       const myId = this.state.activeLink === '#section1' ? '0001' : '0002';
       return (
         <theKeyComponent myID={myID} />
         <otherComponent otherPropsHere={otherProps} />
       )
      }