【发布时间】:2019-09-03 03:38:47
【问题描述】:
大家好, 今天是我第一次使用 redux,我按照 youtube 教程设置了我的样板设置,以使用带有 react-native 的 redux,显然,我遇到了一些问题,并且看不到我可能犯的错误,因为这个概念仍然对我来说有点模糊。
所以我创建了一个简化的、一个动作和一个类型作为起点。问题是在将状态连接到组件并在组件的构造函数中触发操作后,我从操作中获得了结果(使用控制台日志对其进行了测试),但状态没有改变。
这是我的代码:
商店
import {
createStore,
applyMiddleware
} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './src/reducers/rootReducer';
const initialState = {};
const middleware = [thunk];
const store = createStore(rootReducer, initialState, applyMiddleware(...middleware));
export default store;
根减速器
import { combineReducers } from 'redux';
import companyReducer from './companyReducer';
export default combineReducers({
companies: companyReducer
});
公司减速器
import { FETCH_COMPANIES } from '../actions/types';
const initialState = {
values: []
};
export default (state = initialState, action) => {
switch(action.type) {
case FETCH_COMPANIES: return {
...state,
values: action.payload
};
default: return {
test: 'testing'
};
}
}
公司行动
import {
FETCH_COMPANIES
} from './types';
export const fetchCompanies = () => dispatch =>
dispatch({
type: FETCH_COMPANIES,
payload: [{
id: 1,
text: "CHRONUS FRANCE .A."
},
{
id: 2,
text: "two"
},
{
id: 3,
text: "three"
},
{
id: 4,
text: "four"
},
{
id: 5,
text: "five"
},
{
id: 6,
text: "six"
},
{
id: 7,
text: "seven"
},
{
id: 8,
text: "eight"
},
{
id: 9,
text: "nine"
},
{
id: 10,
text: "ten"
},
]
});
类型
export const FETCH_COMPANIES = 'FETCH_COMPANIES';
组件
//imports
import {
connect
} from 'react-redux';
import { fetchCompanies } from '../../actions/companyActions';
//constructor
class Welcome extends Component {
constructor(props) {
super(props);
props.fetchCompanies();
console.log(props);
}
}
//map to props and connect
const mapStateToProps = (state) => ({
companies: state.companies
});
export default connect(mapStateToProps, { fetchCompanies })(Welcome);
这是我在记录道具后在控制台上得到的:
{…}
公司:{…}
test: "testing" <prototype>: Object { … }fetchCompanies: "function () {\n return dispatch(actionCreator.apply(this, arguments));\n }"
navigation: Object { pop: "function () {\n var actionCreator = actionCreators[actionName];\n var action = actionCreator.apply(void 0, arguments);\n return navigation.dispatch(action);\ n }", popToTop: "function () {\n var actionCreator = actionCreators[actionName];\n var action = actionCreator.apply(void 0, arguments);\n return navigation.dispatch(action);\n }" , push: "function () {\n var actionCreator = actionCreators[actionName];\n var action = actionCreator.apply(void 0, arguments);\n return navigation.dispatch(action);\n }", ... }
screenProps:未定义
: 对象 { … } 305278fb-9c91-40bc-b0b1-9fa113a58b1f:93248:15
我希望这里有人能找到什么不起作用以及我错过了什么,并帮助我解决这个问题。 提前感谢您的时间和精力。
【问题讨论】:
-
在
the component你没有导入 React。这是一个错误吗?import {Component} from 'react' -
@chawkichalladia 请试试我的回答。
-
result from the action (tested it with a console log)是什么意思?您能否将日志添加到您的问题中? -
我想你可能想像
console.log(props.fetchCompanies())一样登录。 -
好的,我会在你的回答下评论日志
标签: reactjs react-native redux react-redux