我有一个可配置的应用程序,所有东西都基于唯一的ID(称为appId)从中间件(如颜色和内容)输入到应用程序中。 在主屏幕中,我正在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”已经有一个值(从第一次开始),并且无法再次提供新数据。
从设置页面导航到主页时,是否可以清除所有变量?
答案 0 :(得分:0)
我已经用类似的概念(`componentDidMount()` function is not called after navigation,但是使用了不同的语法解决了我的应用中的相同问题,并且对我有用:
// your home class
// no need to import anything more
// define a separate function to fetch data
fetchData = async () => {
this.setState({ isLoading: true }, async () => {
// fetch your data here, do not forget to set isLoading to false
}
}
// add a focus listener onDidMount
async componentDidMount () {
this.focusListener = this.props.navigation.addListener('didFocus', async () => {
try {
await this.fetchData() // function defined above
} catch (error) {
// handle errors here
}
})
}
// and don't forget to remove the listener
componentWillUnmount () {
this.focusListener.remove()
}