反应:从另一个组件调用setState

时间:2018-10-25 06:53:27

标签: reactjs ecmascript-6

这是父组件:

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 = () => {的{​​{1}}内部触发,以便CustomButton运行ParentupdateNews

2 个答案:

答案 0 :(得分:2)

像这样在父组件中使用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>
  );

请记住,状态切换值是每次单击时更新或获取最新数据的一种简洁,优雅的方法。

答案 1 :(得分: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>
);