问题描述
我正在尝试在React-Native中使用'useEffect'钩子。我正在尝试在场景/脚本之间更改“上下文”变量。我正在使用“ React-Native-Router-Flux”进行导航。这是一些代码:
LogContext.js
import React,{ useState } from 'react'
export const LogContext = React.createContext({
set: "en",login: "false"
})
export const LogContextProvider = (props) => {
const setLog = (login) => {
setState({set: "jp",login: login})
}
const initState = {
set: "en",login: "false"
}
const [state,setState] = useState(initState)
return (
<LogContext.Provider value={state}>
{props.children}
</LogContext.Provider>
)
}
Proceed.js
import React,{ useState,useContext,createContext } from 'react'
import { TouchableOpacity,Text } from 'react-native'
import { Actions } from 'react-native-router-flux'
import { LogContextProvider,LogContext } from './LogContext'
const Proceed = (props) => {
const status = useContext(LogContext);
const goToHome = () => {
Actions.video()
}
React.useEffect(() => {
const unsubscribe = this.props.navigation.addListener('willFocus',() => {
// The screen is focused
// Call any action
status.setState({ set: 'ddd',login: 'true' })
console.log('didFocus');
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
},Actions.home());
return (
<TouchableOpacity style = {{ margin: 128 }} onPress = {goToHome}>
<Text>This is Proceed</Text>
</TouchableOpacity>
)
}
export default Proceed
上面的代码在“ status.setData”行上引发错误。如果我使用“ React.Navagation”而不是“ React-Navigation-Router-Flux”的替代版本,则以下代码将起作用。所以基本上我想将下面的代码转换为使用“ Flux”而不是“ React-Navigation”。例如:
function ProceedScreen({ navigation }) {
const status = React.useContext(LogContext);
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus',() => {
// The screen is focused
// Call any action
status.setData({ set: 'ddd',login: 'true' })
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
},[navigation]);
return (
<View style={{ flex: 1,alignItems: 'center',justifyContent: 'center' }}>
<Text>Video Screen</Text>
<Button title="logout" onPress={() => navigation.navigate('logout')} />
<Text>Passed SET: {JSON.stringify(status.data.set)}</Text>
<Text>Passed LOGIN: {JSON.stringify(status.data.login)}</Text>
</View>
);
}
在此先感谢您的任何建议。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)