再次单击组件时如何再次执行 componentDidMount?

IT技术 reactjs react-redux react-router
2021-04-29 02:21:39

[![在此处输入图像描述][1]][1]

这是我项目的顶部导航栏和 [![在此处输入图像描述][2]][2]

当我单击博客按钮时,将呈现所有博客的列表,并且在此组件中,我现在有一个搜索选项,当我有搜索文本时,让我们说“vue”,然后我将获得所需的结果

handleSubmit = values => {
    const { size } = this.state;
    this.setState({ searchString: values.searchString, isSearch: true });
    SearchSchema.searchString = this.state.searchString;
    this.props.history.push(`/blogs?q=${values.searchString}`);
    this.props.actions.loadBlogs({ page: 0, size, searchString: values.searchString });
  };

这是博客组件的 componentDidMount

componentDidMount = () => {
    const { size } = this.state;
    const params = new URLSearchParams(this.props.location.search);
    const q = params.get('q');
    if (q) {
      this.setState({ searchString: q, isSearch: true });
      this.props.actions.loadBlogs({ page: 0, searchString: q, size });
    } else {
      this.setState({ searchString: '', isSearch: false });
      this.props.actions.loadBlogs({ page: 0, size });
    }
  };

当我再次点击 Top Navbar 中的博客(截图中)时得到结果后,url 已更改但未获取所有博客

<Link className="nav-link" to="/blogs">
            Blogs
          </Link>

带有搜索结果和 url 的屏幕截图将是 http://localhost:8075/blogs?q=vue 当我再次单击博客按钮时,同样的屏幕截图也适用 url 正在更改但博客未更新 http://localhost:8075/blogs

我用这个解决了这个问题

componentDidUpdate(prevProp, prevState) {
    const { size } = this.state;
    const params = new URLSearchParams(this.props.location.search);
    const q = params.get('q');
    if (q !== prevState.searchString) {
      console.log('-------- in if -----------');
      this.setState({ searchString: q });
      this.props.actions.loadBlogs({ page: 0, size });
    }
  }

但不确定这是否正确,并且通过使用它,我仍然在搜索输入字段中获得以前的值

1个回答

这可以用的帮助下完成的componentDidUpdate,你可以比较搜索paramscomponentDidUpdate,当他们differet可以进行更改。

解决方案:

componentDidUpdate(prevProps) {
  if(prevProps.location.search !== this.props.location.search) {
     this.init(); 
  }    
}

componentDidMount {
    this.init();
};

 init = () => {
   const { size } = this.state;
    const params = new URLSearchParams(this.props.location.search);
    const q = params.get('q');
    if (q) {
      this.setState({ searchString: q, isSearch: true });
      this.props.actions.loadBlogs({ page: 0, searchString: q, size });
    } else {
      this.setState({ searchString: '', isSearch: false });
      this.props.actions.loadBlogs({ page: 0, size });
    }    
 }