繁体   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