繁体   English   中英

正确更新反应状态/组件?

[英]Updating the react state/component correctly?

我试图让我的组件对更新做出反应。 我正在使用componentDidUpdate()来检查组件道具 state 是否已更改,然后如果有,我需要调用getPosts() function 并在该道具更改时更新postCount

export default class JsonFeed extends React.Component<IJsonFeedProps, IJsonFeedState> {

  // Props & state needed for the component
  constructor(props) {
    super(props);
    this.state = {
      description: this.props.description,
      posts: [],
      isLoading: true,
      jsonUrl: this.props.jsonUrl,
      postCount: this.props.postCount,
      errors: null,
      error: null
    };
  }

  // This function runs when a prop choice has been updated
  componentDidUpdate() {
    // Typical usage (don't forget to compare props):
    if (this.state !== this.state) {
      this.getPosts();
      // something else ????
    }
  }

  // This function runs when component is first renderd
  public componentDidMount() {
    this.getPosts();
  }

  // Grabs the posts from the json url
  public getPosts() {
    axios
      .get("https://cors-anywhere.herokuapp.com/" + this.props.jsonUrl)
      .then(response =>
        response.data.map(post => ({
          id: `${post.Id}`,
          name: `${post.Name}`,
          summary: `${post.Summary}`,
          url: `${post.AbsoluteUrl}`
        }))
      )
      .then(posts => {
        this.setState({
          posts,
          isLoading: false
        });
      })
    // We can still use the `.catch()` method since axios is promise-based
    .catch(error => this.setState({ error, isLoading: false }));
  }

您可以将componentDidUpdate更改为:

componentDidUpdate() {
    if (this.state.loading) {
      this.getPosts();
    }
  }

这不会是一个无限循环,因为 getPosts() function 将 state 加载为 false;

现在,每次您需要更新时,只需将 state 加载设置为 true。

如果您想要做的是每次jsonUrl更新时加载,那么您需要类似:

componentDidUpdate(prevProps) {
      if (prevProps.jsonUrl!== this.props.jsonUrl) {
         this.getPosts();
      }
}

另外,我不明白您为什么通过公开 componentDidMount 来公开您的组件 state 。

修改您的 getPosts 以接收 jsonUrl 参数并将以下 function 添加到您的 class 中:

static getDerivedStateFromProps(props, state) {
  if(props.jsonUrl!==state.jsonUrl){
    //pass jsonUrl to getPosts
    this.getPosts(props.jsonUrl);
    return {
      ...state,
      jsonUrl:props.jsonUrl
    }
  }
  return null;
}

你可以去掉componentDidUpdate function。

如果您没有在构造函数中设置 state jsonUrl,您也可以从 didmount 中删除 getPosts。

 // This function runs when a prop choice has been updated
   componentDidUpdate(prevProps,prevState) {
   // Typical usage (don't forget to compare props):
   if (prevState.jsonUrl !== this.state.jsonUrl) {
     this.getPosts();
     // something else ????
    }
   }

这样你必须匹配更新的 state

尝试这样做

componentDidUpdate(prevState){
if(prevState.loading!==this.state.loading){
//do Something
    this.getPosts();

}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM