我使用Redux和React Native来管理状态。我相信我已经成功建立了商店和提供者。我可以在任何组件中成功使用store.getState()
和store.dispatch(action())
,但是react-redux connect
函数不允许我从子组件访问商店。您可以在下面的代码中找到任何问题吗?
Login.js-我正在测试的此子组件将无法通过react-redux connect访问redux存储。
import React, {Component} from 'react';
import actions from '../../redux/actions';
import {connect} from 'react-redux';
const mapStateToProps = state => {
// To test if this function fires, which it is not
console.log('login state mapping through redux');
return {
state: state,
};
};
const dispatchToProps = dispatch => {
return {
userRecieved: (user) => dispatch(actions.userRecieved(user)),
};
};
export class Login extends Component {
constructor(){
super();
this.state = {
credentials: {
email: '',
password: '',
},
};
}
componentDidMount(){
// This will show whether redux is connected
console.log(this.props.state);
this.props.userRecieved('TEST USER');
}
render() {
return ( <Text>{this.props.state}</Text> );
}
}
export default connect(mapStateToProps, dispatchToProps)(Login);
App.js
import React, {Component} from 'react';
import YEET from './src/YEET.js';
import store from './src/redux/stores/index';
import {Provider} from 'react-redux';
export default class App extends Component {
render() {
return (
<Provider store={store}>
<YEET />
</Provider>
);
}
}
我的Redux文件:
store.js
import { combineReducers, createStore} from 'redux';
import accountReducer from '../reducers/accountReducer';
import postReducer from '../reducers/postReducer';
const initialState = {};
const reducers = combineReducers({
account: accountReducer,
post: postReducer,
});
const store = createStore(reducers, initialState);
export default store;
actions.js
import constants from '../constants';
var userRecieved = user => ({
type: constants.USER_RECIEVED,
data: user,
});
export default {
userRecieved,
};
accountReducer.js
import constants from '../constants';
var initialState = {
user: {
photos: [],
},
};
export default (state = initialState, action ) => {
let newState = Object.assign({}, state);
switch (action.type) {
case constants.USER_RECIEVED:
const user = {
id: action.data.uid,
// photos: action.data,
};
console.log(action);
newState.user = user;
return newState;
default:
return state;
}
};
答案 0 :(得分:2)
据我所知,唯一的原因可能是您要导入未连接的组件。
导入Login
组件时,请确保导入default
导出而不是named
导出。
因此,无论您在哪里导入Login
组件,都应这样做:
import Login from 'your-login-component-location/Login'
代替
import { Login } from 'your-login-component-location/Login'
第二个是命名导出,它将直接返回Login
类。
第一个是默认导出,它将返回connected
组件。