我有一个可配置的应用程序,它的一切都是从一个中间件(如颜色和内容),基于唯一的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“已经有一个值(从第一次),不能再提供新的数据。
当从设置页面导航到主页时,有没有办法清除所有变量?
发布于 2019-05-01 17:22:43
我已经在我的应用程序中解决了同样的问题,使用了类似的概念( 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()
}
https://stackoverflow.com/questions/55939850
复制相似问题