繁体   English   中英

setState 未更新子组件中的输入值

[英]Input value in child component not being updated by setState

在这个应用程序中,我从 Unsplash API 获取图像(带有 Express 后端,React 前端)。 在页面加载时,会出现一般图像(在react-infinite-scroll-component内渲染),如果您搜索,则会调用特殊的 fetch 方法( fetchSearchImages )来获取新图像。 在任何一种情况下,它们都会在react-infinite-scroll-component实例中呈现。

我的问题是提交包含搜索输入的表单后,搜索输入没有被清除。 在输入中我有value={props.inputValue} ,并且在父组件中,在提交表单后调用fetchSearchImages fetchSearchImages中,我尝试使用this.setState()重置输入值,但输入中显示的值保持不变。 我也尝试在handleSubmit() else 块中这样做,但这也没有做任何事情。

现场观看| GitHub 回购

子搜索输入组件:

const SearchInput = props => {

  const onSubmit = e => {
    // Prevents GET request/page refresh on submit
    e.preventDefault();
    props.onFormSubmit();
  };

  return (
    <form onSubmit={onSubmit}>
      <div className="control">
        <input autoFocus value={props.inputValue} onChange={e => props.onSearch(e.target.value)} className="input" type="text" placeholder="Search" />
      </div>
    </form>
  );
}

父组件:

export class Images extends Component {
  state = {
    images: [],
    searchImages: [],
    count: 4,
    page: 1,
    searchPage: 1,
    term: '',
    search: false,
    newSearch: false,
    blankSearch: false,
    inputValue: ''
  };

  componentDidMount() {
    const { page, count } = this.state;
      axios
        .get(`/api/photos?page=${page}&count=${count}`)
        .then(res => this.setState({ images: res.data }));
    // To prevent same images being fetched upon scrolling (in the first call to fetchImages)
    this.setState({ page: page + count });
  }

  fetchImages = () => {
    const { page, count, images } = this.state;
    this.setState({ page: page + 1 });
    axios
      .get(`/api/photos?page=${page}&count=${count}`)
      .then(res =>
        this.setState({ images: images.concat(res.data) })
      );
  }

  fetchSearchImages = () => {
    const { searchPage, count, term, searchImages } = this.state;

    this.setState({ searchPage: searchPage + 1, inputValue: '' });

    axios
      .get(`/api/photos/search?term=${term}&page=${searchPage}&count=${count}`)
      .then(res =>
        this.setState({
          searchImages: searchImages.concat(res.data.results)
        })
      );
  }

  // Necessary to place fetchSearchImages in a setState callback to ensure other state is set first
  handleSubmit = () => {
    if (!this.state.inputValue) {
      this.setState({
        images: [],
        blankSearch: true,
        newSearch: false,
        search: false,
        searchImages: [],
        searchPage: 1,
        page: 1,
      }, this.fetchImages);
    } else {
      this.setState({
        term: this.state.inputValue,
        searchImages: [],
        searchPage: 1,
        page: 1,
        search: true,
        newSearch: true
      }, this.fetchSearchImages);
    }
  }

  handleInputChange = (e) => {
    this.setState({
      inputValue: e
    });
  }

  render() {
    return (
      <>

      <SearchInput onSearch={this.handleInputChange} value={this.state.inputValue} onFormSubmit={this.handleSubmit} />

      <div className="images">
        <InfiniteScroll
          dataLength={this.state.blankSearch ? this.state.images.length : (this.state.newSearch || this.state.search) ? this.state.searchImages.length : this.state.images.length}
          next={this.state.search ? this.fetchSearchImages : this.fetchImages}
          hasMore={true}
          loader={
            <div className="loader-dots">
              <span className="loader-dot"></span>
              <span className="loader-dot"></span>
              <span className="loader-dot"></span>
              <span className="loader-dot"></span>
            </div>
          }
        >
        {this.state.newSearch || this.state.search ? this.state.searchImages.map(image =>
          <Image key={image.id + Math.random()} image={image} />
        ) : this.state.blankSearch ? this.state.images.map(image =>
          <Image key={image.id + Math.random()} image={image} />
        ) : this.state.images.map(image =>
          <Image key={image.id + Math.random()} image={image} />
        )}
      </InfiniteScroll>
      </div>

      </>
    );
  }
}

看起来您的输入没有得到适当的控制。

在您的SearchInput组件中,您引用了一个无效的道具。 您在父级中调用道具value ,但在子级中将其作为inputValue引用。

将输入更改为:

<input autoFocus value={props.value} onChange={e => props.onSearch(e.target.value)} className="input" type="text" placeholder="Search" />

或家长:

<SearchInput onSearch={this.handleInputChange} inputValue={this.state.inputValue} onFormSubmit={this.handleSubmit} />

暂无
暂无

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

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