React:从另一个组件调用 setState

Ama*_*day 5 ecmascript-6 reactjs

这是父组件:

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

  updateNews = () => {
      ...
  }

  render() {
      <CustomButton type="primary"  />
  }
Run Code Online (Sandbox Code Playgroud)

这是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>
  );
Run Code Online (Sandbox Code Playgroud)

我怎样才能从内向const updateItem = () => {内开火CustomButton,以便Parent跑动updateNewscomponentDidMount

Tha*_*hik 5

像这样在父组件中使用 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} />
  }
Run Code Online (Sandbox Code Playgroud)

在子组件中单击按钮调用此切换函数。

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>
  );
Run Code Online (Sandbox Code Playgroud)

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