【问题标题】:React Native - How to make a variable global from my fetch methodReact Native - 如何从我的 fetch 方法中创建一个全局变量
【发布时间】:2026-01-03 01:55:02
【问题描述】:

所以我有一个方法可以获取一个 api,从它的表 ID 中获取最大值,然后将该值赋给一个全局变量。

但是 componentDidMount 稍后会进行获取,因此我的应用会显示“未定义”,而不是先获取然后将值分配给变量。

代码:

constructor(props) {
    super(props);
    this.state = {
        data: [],
        id: '',
    };
}



fetchData = () => {
            fetch(url)
                .then(request => request.json())
                .then(response => {
                    this.setState({
                        data: response,
                        id:Math.max.apply(Math, response.map(function (o) { return o.id; })) + 1,
                    });
console.log(this.state.id) // this gives me the highest id + 1 /here it works but check the render method!
                });
        }


componentDidMount = () => {
            this.fetchData();
        }


render() {
    return (
        <View
            style={styles.container}
        >
            <ScrollView>
                <TextInput
                    style={styles.input}
                    placeholder={this.state.id} //here it uses the original states value which is empty ('') and not the one from the fetch' setState...why?
                    onChangeText={(text) => this.updateValue(text, 'id')}
                />

            </ScrollView>

        </View>
    );
  }
}

【问题讨论】:

  • 如果渲染没有得到更新的值,看起来 fetch 调用不起作用??
  • 能不能在返回前console.log(this.state)?
  • 不要把它放在全局中,你可以很容易地让它在状态下工作。我们只需要更多信息,关于什么是响应以及渲染后的状态是什么。同样在这里你得到未定义,因为 global.id 在你填充它之前不存在。
  • 这是在安卓里吗?
  • 我知道这是 react-native,我的意思是 android textinput 占位符,如果我记得不要重新渲染,你能用 value 试试看是否有效吗?

标签: javascript api react-native fetch state


【解决方案1】:

只需将其添加到global 范围。 例如:global.myVar = "my global variable"

【讨论】:

  • 现在当我做一个console.log(global.id)。它说未定义。它还在 fetch 之前打印出来,所以它可能与 react native 在之后执行 fetch 方法有关?所以您的回复有效,但我发现问题出在其他地方。
  • 是的,当 fetch 完成时打印 console.log,当 promise 解决时。
  • 当然,这给了我想要的数字,但我需要 textinput 中的那个值作为占位符,即使我使用 fetch 方法中的全局变量,它也保持未定义,它给出了正确的数字.
  • 这是一个不同的问题 :) 在此之前,请将初始问题的答案标记为确定。关于你的新问题,我想你应该在state 中设置你的占位符并将state 更改为global.yourVar
最近更新 更多