gpt4 book ai didi

javascript - React-Redux 连接无法从 Provider 获取存储

转载 作者:行者123 更新时间:2023-12-01 00:18:32 24 4
gpt4 key购买 nike

我使用 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;
}
};

最佳答案

据我所知,唯一的原因可能是您正在导入未连接的组件。

导入 Login 组件时,请确保导入 default 导出而不是 named 导出。

因此,无论您在何处导入 Login 组件,都可以这样做:

import Login from 'your-login-component-location/Login'

而不是

import { Login } from 'your-login-component-location/Login'

第二个是命名导出,它将直接返回Login类。第一个是默认导出,它将返回 connected 组件。

关于javascript - React-Redux 连接无法从 Provider 获取存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59595181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com