所以我正在为我的项目准备 redux 并陷入困境。 所有事情看起来都是正确的,因为 redux devtools 显示了状态。
当我尝试通过 this.props.function_name 调用组件中的函数时出现问题
我在 .then() 中进行了该调用,因为我在 axios 返回 token 时调用它,我知道该范围在 then 中发生变化,但我在 then 中使用箭头函数,所以问题似乎不存在.
还尝试从另一个函数调用 this.props.setcurrent ,但是得到了 _this2 未定义 我的代码:
Signup.js
import {setCurrent} from '../actions/authActions'
class SignUp extends Component {
constructor(props) {
super(props);
}
responseGoogle(response) {
console.log('google', response);
const access_token = response.Zi.access_token;
axios
.post('http://localhost:3001/users/oauth/google', {
access_token
})
.then((response) =>{
console.log('google', response);
const decoded = jwt_decode(response.data.token);
this.props.setCurrent(decoded);
console.log(decoded);
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<GoogleLogin
clientId="890644813294-bvuq6cf7lsilohneqvov28oi60sfdmig.apps.googleusercontent.com"
buttonText="Login"
onSuccess={this.responseGoogle}
onFailure={this.responseGoogle}
/>
)
}
}
export default connect(null, { setCurrent })(SignUp);
authActions.js
import { TEST_DISPATCH } from './types';
// Testing
export const setCurrent = (userToken) => {
return {
type: TEST_DISPATCH,
payload: userToken
};
};
authReducer.js
import { TEST_DISPATCH } from '../actions/types';
const initialState = {
isAuthenticated: false,
user: {}
}
export default function(state = initialState, action) {
switch(action.type) {
case TEST_DISPATCH:
return {
...state,
user: action.payload
};
default:
return state;
}
}
Auth/index.js
import { combineReducers } from 'redux';
import authReducer from './authReducer';
export default combineReducers({
auth: authReducer
});
store.js
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const initialState = {};
const middleware = [thunk];
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(...middleware),
// window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
export default store;
App.js
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import store from '../store';
import LogIn from './LogIn';
import SignUp from './SignUp';
class App extends Component {
render() {
return(
<Provider store={ store }>
<div>
<h1>SignUp!</h1>
<SignUp />
</div>
</Provider>
)
}
}
export default App;
完整代码:https://github.com/ExadelPraktika/Front-exabook/tree/auth 我还在 webpack 中使用 babel
最佳答案
i know that scope of this changes in then, but I'm using arrow function with then so the problem seems not to be there.
这仍然是一个范围问题。方法responseGoogle 是有作用域的。所以你需要像这样“自动绑定(bind)”它:
responseGoogle = (response) => {/* 您的代码 */}
或 在 SignUp 组件的渲染方法中:
<GoogleLogin
onSuccess={response => this.responseGoogle(response)}
onFailure={response => this.responseGoogle(response)}
/>
关于javascript - React/Redux 无法读取未定义的属性 'setCurrent',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51253413/