React:从另一个组件调用setState

问题描述 投票:2回答:2

这是父组件:

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      news: ""
    }
  }
  componentDidMount() {
    this.updateNews();
  }

  updateNews = () => {
      ...
  }

  render() {
      <CustomButton type="primary"  />
  }

这是CustomButton

const CustomButton = (props) => {
  const {
    type
  } = props;


  const updateItem = () => {
     ... // The firing of the setState should be here
  }

  return (
   <Button
    type={type}
    onClick={() => {
        updateItem();
      }}
    >{value}
   </Button>
  );

我怎么能从const updateItem = () => {CustomButton里面射击,以便Parent运行updateNewscomponentDidMount

reactjs ecmascript-6
2个回答
2
投票

像这样在Parent组件中使用componentDidUpdate。

class Parent extends Component {
  constructor(props) {
   super(props);
   this.state = {
    news: "",
    fetchToggle:true
   }
  }
  componentDidMount() {
   this.updateNews();
  }

  componentDidUpdate(prevprops,prevstate){
    if(prevstate.fetchToggle!==this.state.fetchToggle){
       this.updateNews();
    }
  }
  updateNews = () => {
   ...
  }
  fetchToggle=()=>{
     this.setState({
      fetchToggle:!this.state.fetchToggle;
     })
   }

  render() {
    <CustomButton type="primary" fetchToggle={this.fetchToggle} />
  }

在子组件中单击按钮调用此切换功能。

const CustomButton = (props) => {
  const {
   type
  } = props;

  const updateItem = () => {
   ... // The firing of the setState should be here
  } 

  return (
   <Button
     type={type}
     onClick={() => {
       props.fetchToggle()
     }}
   >{value}
   </Button>
  );

请记住,状态中的切换值是一种更清晰,更优雅的方式,可以在每次单击时更新或获取最新数据。


0
投票

您应该将回调函数传递给CustomButton,类似于:

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      news: ""
    }
  }
  componentDidMount() {
    this.updateNews();
  }

  updateNews = () => {
      ...
  }

  render() {
      <CustomButton type="primary"  stateUpdatingCallback={(val) => {this.setState({myVal: val})}}/>
  }


const CustomButton = (props) => {
  const {
    type
  } = props;


  const updateItem = () => {
     ... // The firing of the setState should be here
  }

  return (
   <Button
    type={type}
    onClick={() => {
        this.props.stateUpdatingCallback("somevalue")
      }}
    >{value}
   </Button>
);
© www.soinside.com 2019 - 2024. All rights reserved.