【发布时间】:2019-09-20 05:34:03
【问题描述】:
我有一个可配置的应用程序,它基于一个名为 appId 的唯一 ID,从中间件(如颜色和内容)向应用程序输入所有内容。 在主屏幕中,我从 componentDidMount() 函数中的中间件获取所有需要的数据,然后稍后使用它。我第一次使用默认的 appId,componentDidMount() 看起来像这样:
componentDidMount() {
this.setState({ isLoading: true });
fetch(
API +
"configurations" +
"?" +
"uuid=blabla" +
"&" +
"appId=" +
appId +
"&" +
"locale=" +
locale +
"&" +
"gid=" +
gid,
{
method: "GET",
headers: {
Accept: "application/json"
}
}
)}
我有另一个屏幕(设置屏幕),其中有一个框,用户可以插入 appId 作为输入。
当用户插入 appId 时(在设置页面中),我想导航回主屏幕并使用用户插入的新 appId 重新获取数据。设置画面如下:
state = {
newappId: "" };
handlenewappId = text => {
this.setState({ newappId: text });
};
.....
<Item regular>
<Input
onChangeText={this.handlenewappId}
placeholder="Regular Textbox"
/>
<Button
onPress={() => {
navigation.navigate("Home");
}}
>
<Text>Save</Text>
</Button>
</Item>
但是,当我执行 navigation.navigate("Home") 时,不会触发 componentDidMount() 以便再次从中间件获取数据(这是预期的,因为它只是第一次触发)。 我该怎么办?解决办法是什么?
我已经尝试过`componentDidMount()` function is not called after navigation给出的解决方案 但它对我不起作用。
还尝试将 componentDidMount() 中的代码移动到单独的函数中并从设置页面调用它,但我无法使其工作。
============== 更新:==============
我能够通过下面“vitosorriso”给出的答案解决这个问题。然而,一个新的问题出现了。获取完成后,我将响应推送到状态,然后像这样在我的主屏幕上使用它:
fetchData = async () => {
this.setState({ isLoading: true }, async () => {
//fetch the data and push the response to state. e.g:
this.setState({ page: data, configs: data2, isLoading: false });
}}
....
render() {
const { configs, page, isLoading, error } = this.state; //getting the data fetched in the fetch function and pushed to the state
if (isLoading || !page || !configs) {
//if data is not ready yet
);
// Use the data to extract some information
let itemMap = page.item.reduce((acc, item) => {
acc[item.id] = item;
item.attributes = item.attributes.reduce((acc, item) => {
acc[item.key] = item.value;
return acc;
}, {});
return acc;
}, {});
}}
应用程序第一次启动时,一切正常,没有错误,但如果我进入设置页面并按下按钮导航回到主屏幕并再次获取数据,我会遇到错误: “items.attributes.reduce 不是函数”。 我假设原因是,“items.attributes”已经有一个值(从第一次开始)并且不能再次输入新数据。
从设置页面导航到主页时,有什么方法可以清除所有变量?
【问题讨论】:
标签: react-native