状态更改时重新渲染另一个组件

时间:2019-09-29 12:11:22

标签: reactjs

状态更改后,我想重新渲染另一个组件。我有条件的组件。其中之一与我主要组件中的输入有关。它首先被渲染,但是当我更改输入值(也就是状态值)时,我无法重新渲染它。组件为SearchGifList

import React from 'react';
import logo from './logo.svg';
import './App.css';
import TrendingGifList from './TrendingGifList';
import SearchGifList from './SearchGifList';



class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        value: '',
        search: false
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    event.preventDefault();
    this.setState({
      search : true,
    })
  }
  getTrendingGifs = () => {
    this.setState({
      search : false,
      value: ''
    })
  }

  getComponent = () => {
    if(this.state.search) {
      return <SearchGifList value={this.state.value} />
    }
    else {
      return <TrendingGifList />
    }
  }
  render() {
    return (
      <>    
            <div>
                <a onClick={this.getTrendingGifs}>Logo</a>
                <form onSubmit={this.handleSubmit}>
                  <input className="input-search" type="text" value={this.state.value} onChange={this.handleChange} />
                  <button type="submit" >Search</button>
                </form>
            </div>
            <div>
                {this.getComponent()}
            </div>
      </>
    ); 
  }
}

export default App;

SearchGifList组件代码:

import React, { Component } from 'react';
import Masonry from 'react-masonry-css';
import {API_KEY, API_URL_search} from './constants'

class SearchGifList extends Component {
    constructor(props) {
        super(props);
        this.state = {
          error: null,
          isLoaded: false,
          items: [],
          breakpointColumnsObj : {
            default: 4,
            1100: 3,
            700: 2,
            500: 1
            },
            offset: 0,
            limit: 20,
            api_key: API_KEY,
            total_count: 0,
            value: this.props.value
        };
      }


    searchGifs = () => {
      fetch( API_URL_search + 
      "?q=" + this.state.value +
      "&api_key=" + this.state.api_key + 
      "&limit=" +  this.state.limit +
      "&offset=" + this.state.offset)
          .then(res => res.json())
          .then(
            (result) => {
                this.setState({
                isLoaded: true,
                items: (this.state.items).concat(result.data),
                total_count: result.pagination.total_count,
                offset : this.state.offset + 20
              });

            },
            (error) => {
              this.setState({
                isLoaded: true,
                error : 'Somethings went wrong to search gifs.'
              });
            }
          )
    }

      componentDidMount() {
        this.searchGifs();
      }

      loadMore = () => {
        if(this.state.offset < this.state.total_count){
          this.setState({
            offset : this.state.offset + 20
          });
        }
        this.searchGifs();
      }


    render() {
        const { error, isLoaded, items } = this.state;
        if (error) {
        return <div>Error: {error.message}</div>;
        } else if (!isLoaded) {
        return <div>Loading...</div>;
        } else {
        return (
            <>

                <Masonry
                breakpointCols={this.state.breakpointColumnsObj}
                className="my-masonry-grid"
                columnClassName="my-masonry-grid_column"
                >
                    {items.map(item => (
                        <div className="gif-container" >
                            <img className="gif-preview" height={item.images.fixed_width.height} src={item.images.fixed_width.webp} alt="giphy baby" />
                        </div>

                    ))}
                </Masonry>

                <button onClick={this.loadMore}>Load More</button>
            </>
        );
        }
    }

}

export default SearchGifList;

2 个答案:

答案 0 :(得分:0)

它应该在更改状态后呈现内容。这是我现在为您创建的一个类似示例。 https://codesandbox.io/embed/example-ys041

请检查一下,我认为这会对您有很大帮助。

如果您仍然不知道任何想法,请通过codeandbox将您的示例发送给我,我会帮您检查。

谢谢

答案 1 :(得分:0)

我解决了问题componentDidUpdate()方法:

componentDidUpdate(prevProps) {
        if (this.props.value !== prevProps.value) {

          setTimeout(() => {
            this.setState({
            items: [],
            offset: 0
          }, function(){
            this.searchGifs();
            });
          }, 10)

        }
      }

谢谢所有答案