繁体   English   中英

在道具更改时重置 State

[英]Reset State on Props Change

所以,我有三个组件(搜索、页面、HandlesApi)加上 App.js,我通过函数将道具传递给其他子组件没有问题。

Search 组件将其用户输入的 state 传递给 HandleApi 组件,并使用 componentDidUpdate 更新 api。 (这很好用,np here)。

我添加了 Pages 组件来更新 api 的页码,以便用户可以循环浏览内容页面。 这有效,但有问题。 用户可以进行搜索并循环浏览页面,但如果他们输入新查询,他们将登陆新查询的相同页码。 例如,如果我搜索“鸭子”并单击下一页(2)。 然后搜索“狗”,他们将登陆“狗”的第二页

所以我的问题是如何仅在用户输入新查询时为我的 Pages 组件重置 state?

我看到 componentWillReceiveProps 已被弃用,所以我不能使用它。 getDerivedStateFromProps 似乎是个好主意,但从我读到的内容来看,它应该只在极少数情况下使用。

所以,两个最有可能的选择似乎是,以我不理解的方式使用 componentDidUpdate 或使用密钥?

总的来说,我只是对该怎么做感到困惑

在我的 HanddlesApi 组件中,我将以下内容传递给 API:

q: this.props.inputValue ? this.props.inputValue : 'news',
page: this.props.pageNum ? this.props.pageNum: 0

然后..

  componentDidMount() {
        this.fetchNews()
    }

    componentDidUpdate(prevProps, prevState) {
        if (this.props.inputValue !== prevProps.inputValue || this.props.pageNum !== prevProps.pageNum) {
            this.setState({
                news: []
            }, this.fetchNews);
        }
    }

然后在我的页面组件中,我有

import React, { Component } from 'react'


class Pages extends Component {
    constructor(props) {
        super(props)
        this.state = {
            nextPage: 1,
            prevPage: 0

        }

    }
    handleNextClick = () => {
        this.setState({
            nextPage: this.state.nextPage + 1,
        })
    }

    handlePrevClick = () => {
        this.setState({
            prevPage: this.state.prevPage - 1,

        })
    }

    render() {
        return (
            <div className='pageNav'>
                <button className="PrevButton" onClick={() => {
                    this.handlePrevClick()
                    this.props.onNextButtonClick(this.state.prevPage)
                }}>Previous </button>

                <button className="nextButton" onClick={() => {
                    this.handleNextClick()
                    this.props.onNextButtonClick(this.state.nextPage)
                }}>Next </button>
            </div>
        )
    }

}

export default Pages

搜索组件

import React, { Component } from 'react';

class SearchBar extends Component {
    constructor(props) {
        super(props)
        this.state = {
            inputValue: ""
        }
    }
    handleChange = (e) => {
        this.setState({
            inputValue: e.target.value
        })
    }

    handleSubmit = (e) => {
        e.preventDefault()
        this.props.onSubmittedSearch(this.state.inputValue)
    }

    render() {
        //{this.props.onSubmittedSearch(this.state.inputValue)} 
        return (
            <section>
                <form onSubmit={this.handleSubmit}>
                    <label htmlFor="searching"></label>
                    <input type="text" placeholder="Search Something" value={this.state.inputValue} onChange={this.handleChange} />
                    <button type="submit">Search </button>
                </form>

            </section>
        )
    }

}

export default SearchBar

应用程序.js

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      inputValue: null,
      pageNum: 1

    }
  }
  // used to pass props from SearchBar to NewsList
  onSubmittedSearch = (inputValue) => {
    this.setState({
      inputValue: inputValue
    })
  }
  onNextButtonClick = (pageNum) => {
    this.setState({
      pageNum: pageNum

    })
  }



  render() {
    return (
      <main>


        <SearchBar onSubmittedSearch={this.onSubmittedSearch} />


        <NewsList inputValue={this.state.inputValue} pageNum={this.state.pageNum} />


        <Pages onNextButtonClick={this.onNextButtonClick} />
        <Footer />


      </main>
    )
  }
}

export default App;

您应该让 App 负责更改和保存当前页码。 因此,您可以在每次提交搜索组件时重置它。 这是一个工作示例:

 class Pages extends React.Component { render() { return (<div className='pageNav'> <button disabled={this.props.page <= 1} className="PrevButton" onClick={this.props.onPrevButtonClick}>Previous </button> <span>{this.props.page}</span> <button className="nextButton" onClick={this.props.onNextButtonClick}>Next </button> </div>) } } class SearchBar extends React.Component { constructor(props) { super(props) this.state = { inputValue: "" } } handleChange = (e) => { this.setState({inputValue: e.target.value}) } handleSubmit = (e) => { e.preventDefault() this.props.onSubmittedSearch(this.state.inputValue) } render() { //{this.props.onSubmittedSearch(this.state.inputValue)} return (<section> <form onSubmit={this.handleSubmit}> <label htmlFor="searching"></label> <input type="text" placeholder="Search Something" value={this.state.inputValue} onChange={this.handleChange}/> <button type="submit">Search </button> </form> </section>) } } class App extends React.Component { constructor(props) { super(props) this.state = { inputValue: null, pageNum: 1 } } // used to pass props from SearchBar to NewsList onSubmittedSearch = (inputValue) => { this.setState({inputValue: inputValue, pageNum: 1}) } onNextButtonClick = () => { this.setState(state => ({ pageNum: state.pageNum + 1 })) } onPrevButtonClick = (pageNum) => { this.setState(state => ({ pageNum: Math.max(state.pageNum - 1, 1) })) } render() { return (<main> <SearchBar onSubmittedSearch={this.onSubmittedSearch}/> <Pages onNextButtonClick={this.onNextButtonClick} onPrevButtonClick={this.onPrevButtonClick} page={this.state.pageNum}/> </main>) } } ReactDOM.render(<App/>, document.getElementById('root'));
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>

暂无
暂无

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

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