React 在 setState 之后不更新组件

React doesn't update component after setState

我在 React 中更新组件时遇到问题。我的 Autocomplete 组件的 defaultValue 属性 链接到 this.state.tags。在执行 render() 方法时,尚未获取 this.state.tags 数组,因此它在组件中设置为空。当 this.state.tags 数组设置为其获取的值时,Autocomplete 不会被 React 更新。

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;

工作 Codesandbox 样本与假 api。