为什么我的React Navigation setParams不更新已安装组件的数据?
const NewScreen = props => {
const [extraInfo, setExtraInfo] = useState({
title: '',
description: '',
});
const [mediaArray, setMediaArray] = useState(null);
const [someData, setSomeData] = useState({});
const grabData = useCallback(() => {
return axios
.get('url')
.then(res => {
/* does some data grabbing for setSomeData and setMediaArray */
setSomeData({
data1,
data2,
data3,
});
setMediaArray(media);
})
.catch(err => console.log('axios catch err', err));
}, []);
/* ... more data grabbing for extraInfo */
useEffect(() => {
grabData();
props.navigation.setParams({
mutate: props.mutate,
title: extraInfo.title,
description: extraInfo.description,
newDataForAray: mediaArray,
...someData,
});
}, [grabData]);
return (
<KeyboardAvoidingView behavior="padding" style={styles.keyboardView}>
...
</KeyboardAvoidingView>
);
};
NewScreen.navigationOptions = props => {
const {mutate, title, description, newDataForAray} = props.navigation.state.params;
const handleSubmit = () => {
mutate({
variables: {
title,
description,
},
});
};
return {
headerRight: () => (
<TouchableOpacity
onPress={() => handleSubmit()}
style={{marginRight: 10}}>
<Text>Done</Text>
</TouchableOpacity>
),
};
};
const mutation = gql`
mutation someMutation(
...
) {
...
}
`;
export default graphql(mutation)(withNavigation(NewScreen));
所以在加载时,我可以通过axios
获取数据。但是当组件挂载时,prop.navigation.setParams
中的数据不会被填充。如果我将someData, mediaArray or extraInfo
添加到useEffect回调的数组中,它将无限循环,重新渲染我的组件,但navigation.state
中的数据将最终填充。
我希望能够将值传递到导航状态,这样我就可以在标题中使用它
使用当前设置,grabData
将提取数据,但在下一次渲染之前不会刷新someData
、mediaArray
等。但是,下一次渲染不会运行,因为useEffect的依赖数组不会触发。
您可以使用两个useEffects
,其中一个保留给grabData
,另一个保留为props.nav
。更好的是,在grabData
中更新props.nav
。
反映评论的更新
媒体或somedata值不会立即更改。因此,将api提取的相同媒体或某些数据引用到setParams
const grabData = useCallback(() =>
axios
.get('url')
.then(res => {
/* does some data grabbing for setSomeData and setMediaArray */
const someData = {
data1,
data2,
data3,
};
setSomeData(someData);
setMediaArray(media);
const paramsTest = {
mutate: props.mutate,
title: extraInfo.title,
description: extraInfo.description,
newDataForAray: media,
...someData,
};
console.log({ paramsTest }); // used to confirm values provided to nav
props.navigation.setParams(paramsTest);
})
.catch(err => console.log('axios catch err', err)), [props.navigation.setParams]);