簡體   English   中英

在setState之后React不會更新組件

[英]React doesn't update component after setState

我在 React 中更新組件時遇到問題。 我的Autocomplete組件具有鏈接到this.state.tags defaultValue屬性。 在執行render()方法時, this.state.tags數組還沒有被獲取,所以它在組件中被設置為空。 this.state.tags數組設置為其獲取的值時,React 不會更新Autocomplete

constructor(props) {
  super(props);
  this.state = {
    tags:[],
    all_tags:[{tag: "init"}]
  };
}
componentDidMount() {

axios.post('http://localhost:1234/api/issue/getIssueById', {id: this.props.match.params.id}, { withCredentials: true })
  .then(res=>{
  var arr = [];
  res.data.tags.forEach(x=>{
      arr.push({tag: x});
  });
  this.setState((state,props)=>{return {tags: arr}});
})
.catch((e)=>{console.log(e)});
}
render() {

return (
  <Fragment>
      <Autocomplete
             multiple
             defaultValue={this.state.tags[0]}
             onChange={(event, value) => console.log(value)}
             id="tags-standard"
             options={this.state.all_tags}
             getOptionLabel={option => option.tag}
             renderInput={params => (
               <TextField
                 {...params}
                 variant="standard"
                 label="Multiple values"
                 placeholder="Favorites"
                 fullWidth
               />
             )}
           />
      </Fragment>
    );
}

編輯:如果我把它放在render()里面:

    setTimeout(()=>{
      console.log("this.state.tags: ", this.state.tags);
    }, 1000);

this.state.tags設置正確。

您正在使用options={this.state.all_tags}並且在componentDidMount您正在更新狀態中的tags字段。 我認為有問題。

首先,您需要使用this.state.tags作為自動完成中的選項。

其次,您對 setState 的使用似乎有問題。

最后,如果您需要在渲染中填充所有標簽,則需要使用Autocomplete組件的value屬性。

import React, { Fragment, Component } from "react";
import { fetchTags } from "./fakeApi";
import Autocomplete from "@material-ui/lab/Autocomplete";
import TextField from "@material-ui/core/TextField";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tags: [],
      selectedTags: [],
      all_tags: [{ tag: "init" }]
    };
  }

  componentDidMount() {
    fetchTags()
      .then(res => {
       let allTags = res.data.tags.map(el => ({ tag: el }));
        this.setState({
          tags: allTags,
          selectedTags: allTags
        });
      })
      .catch(e => {
        console.log(e);
      });
  }
  onChange = value => {
      this.setState({
        selectedTags: value
      })
  }

  render() {
    return (
      <Fragment>
        <Autocomplete
          multiple
          value={this.state.selectedTags}
          onChange={(event, value) => this.onChange(value)}
          id="tags-standard"
          options={this.state.tags}
          getOptionLabel={option => option.tag}
          renderInput={params => (
            <TextField
              {...params}
              variant="standard"
              label="Multiple values"
              placeholder="Favorites"
              fullWidth
            />
          )}
        />
      </Fragment>
    );
  }
}

export default App;

帶有假 API 的工作Codesandbox示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM