简体   繁体   English

在道具更改时重置 State

[英]Reset State on Props Change

So, I have three components(Search, Pages, HanddlesApi) plus App.js and I'm passing props around via functions to other child components with no problem.所以,我有三个组件(搜索、页面、HandlesApi)加上 App.js,我通过函数将道具传递给其他子组件没有问题。

The Search component passes it's state of userInput to HandleApi component and updates the api using componentDidUpdate. Search 组件将其用户输入的 state 传递给 HandleApi 组件,并使用 componentDidUpdate 更新 api。 (this works great, np here). (这很好用,np here)。

I added the Pages component to update the api's page number so that the user can cycle through pages of content.我添加了 Pages 组件来更新 api 的页码,以便用户可以循环浏览内容页面。 This works, but with issues.这有效,但有问题。 The user can do a search and cycle though the pages, but if they enter a new query, they will land on the same page number of the new query.用户可以进行搜索并循环浏览页面,但如果他们输入新查询,他们将登陆新查询的相同页码。 For example, If I searched "ducks" and clicked to the next page(2).例如,如果我搜索“鸭子”并单击下一页(2)。 Then did a search for "dogs" they would land on page two of "dogs"然后搜索“狗”,他们将登陆“狗”的第二页

So my question is how do I reset state for my Pages component only when a user enters a new query?所以我的问题是如何仅在用户输入新查询时为我的 Pages 组件重置 state?

I saw that componentWillReceiveProps is being deprecated, so I can't use that.我看到 componentWillReceiveProps 已被弃用,所以我不能使用它。 getDerivedStateFromProps seemed like it might be a good idea, but from what I read it should only be used in rare cases. getDerivedStateFromProps 似乎是个好主意,但从我读到的内容来看,它应该只在极少数情况下使用。

So, the two most likely options seemed to be, use componentDidUpdate in a way I don't understand or use key?所以,两个最有可能的选择似乎是,以我不理解的方式使用 componentDidUpdate 或使用密钥?

Overall I'm just confused on what to do总的来说,我只是对该怎么做感到困惑

In my HanddlesApi Component I'm passing the follwoing into the API:在我的 HanddlesApi 组件中,我将以下内容传递给 API:

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

then..然后..

  componentDidMount() {
        this.fetchNews()
    }

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

Then in my Pages Component, I have然后在我的页面组件中,我有

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

Search Component搜索组件

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

App.js应用程序.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;

You should let App in charge of changing and holding the current page number.您应该让 App 负责更改和保存当前页码。 So you can reset it each time your search component submit.因此,您可以在每次提交搜索组件时重置它。 Here is a working exemple:这是一个工作示例:

 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