我正在尝试使用redux设置setState。我正在使用Facebook登录,一旦获得facebookAccessToken
,我想使用redux将其设置为全局状态,然后使用按钮回调全局状态。下面是我的代码:
App.js
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { createDrawerNavigator, createStackNavigator, } from 'react-navigation'
const reducer = (state = '', action) => {
switch (action.type) {
case 'UPDATE':
return { facebookToken: action.payload}
}
return state
}
const store = createStore(reducer)
class App extends Component {
render(){
return(
<Provider store={store}>
<View style={{flex:1,backgroundColor:'transparent'}}>
<AppDrawerNavigator/>
</View>
</Provider>
)
}
}
LoginScreen.js
import { LoginButton, AccessToken } from 'react-native-fbsdk';
import {connect} from 'react-redux'
class LoginScreen extends Component{
render() {
return(
<View>
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
console.log("login has error: " + result.error);
} else if (result.isCancelled) {
console.log("login is cancelled.");
} else {
this.props.navigation.navigate('VerifyScreen')
AccessToken.getCurrentAccessToken().then(
(data) => {
this.setState({facebookToken:data.accessToken},
() => console.log('facebookToken.state',this.state.facebookToken),
//Here I am getting undefined for 'this.props.facebookToken'
() => console.log('facebookToken.props',this.props.facebookToken),
console.log('facebook login success!'),
console.log('facebook token is:',data.accessToken.toString()))
}
)
}
}
}
onLogoutFinished={() => console.log("logout.")}/>
//I created a button to see if I could call global state. but this would give me an error "state is not defined"
<Button
title="call global state"
onPress={() => this.props.updateState()}/>
</View>
)
}
}
function mapStateToProps(state) {
return {
facebookToken: state.facebookToken
}
}
function mapDispatchToProps(dispatch) {
return {
updateState: () => dispatch({ type: 'UPDATE',payload: state.facebookToken }),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen)
我的问题:
1)在我的LoginScreen
中,为什么为什么要为我的{this.props.facebookToken}获取undefined
是因为我没有调用函数“ updateState”?
2)成功登录Facebook后,在“登录屏幕”中,我得到AccessToken
并假设this.props.facebookToken
设置为data.accessToken
。因此,当我按下按钮时,我期望得到globalState
,但它给了我一个错误state
的定义。
我真的是redux的新手,所以任何评论或建议都将非常有帮助。提前致谢!
答案 0 :(得分:1)
对于您的#1问题,您是正确的,因为您没有调用updateState方法。
对于您的#2问题,请尝试此操作。该状态永远不会在该代码块中定义,因为您没有传递状态对象。
function mapDispatchToProps(dispatch) {
return {
updateState: () => dispatch({ type: 'UPDATE', payload: state.facebookToken }),
}
}
将其更改为
function mapDispatchToProps(dispatch) {
return {
updateState: (state) => dispatch({ type: 'UPDATE', payload: state.facebookToken }),
}
}
然后更改
onPress={() => this.props.updateState()}
到
onPress={() => this.props.updateState(this.state)}