【问题标题】:I need to update an api inside a componentDidMount after I setState in a render在渲染中设置状态后,我需要更新 componentDidMount 中的 api
【发布时间】:2019-05-15 07:19:56
【问题描述】:

我在 componentDidMount 中使用 fetch 调用了 API,但我需要 API URL 来更改我在 textInput 中设置的状态。

我可以在 console.log() 中看到我的状态正在改变,但它似乎在 componentDidMount 内部没有改变。

constructor(props) {
    super(props)
    this.state = {
      codigoCarro: "", //this is the state i need to change
    }
  } 

 componentDidMount() {

fetch
(`https://parallelum.com.br/fipe/api/v1/carros/marcas/${this.state.codigoCarro}/modelos`) //i need the state to change here
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          modeloCarro: responseJson.modelos
        })
      })
      .catch((error) => {
        console.log(error)
      })
  }

 render() {
      return (
              <Text>Please insert the number informed in the input below</Text>
              <TextInput
                placeholder="Código da marca"
                onChangeText={(codigoCarro) => { 
                  this.setState({ codigoCarro }); 
                }}
              />


      );
    }

【问题讨论】:

  • modeloCarro不在状态
  • 没有输入,没有更改处理程序,不要在渲染中setState - 阅读文档

标签: javascript reactjs react-native state


【解决方案1】:

可能值得阅读 React documentation for componentDidMount() 的内容,因为此函数仅在组件插入 dom 树后才会调用,这意味着每次状态更新时都不会调用它。

您可能正在寻找在每次渲染后调用的 componentDidUpdate() 函数,但是,我仍然会阅读文档,因为您可能会通过更改它来引入过多的网络请求。

最终产品可能如下所示:

componentDidUpdate(prevProps, prevState) {

    if(prevState.codigoCarro == this.state.codigoCarro) return;

    fetch
    (`https://parallelum.com.br/fipe/api/v1/carros/marcas/${this.state.codigoCarro}/modelos`) //i need the state to change here
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                modeloCarro: responseJson.modelos
            })
        })
        .catch((error) => {
            console.log(error)
        })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    相关资源
    最近更新 更多