在渲染器中设置状态后,我需要在componentDidMount中更新一个api

时间:2019-05-15 07:19:56

标签: javascript reactjs react-native state

我使用componentDidMount内部的访存调用了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 }); 
                }}
              />


      );
    }

1 个答案:

答案 0 :(得分:2)

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

您可能正在寻找在每个渲染之后调用的componentDidUpdate()函数,但是,我仍然会阅读文档,因为您可能会通过更改此内容引入过多的netowrk请求。

最终产品可能看起来像这样:

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)
        })
}