我一直在设置redux时遇到麻烦,我有mapStateToProps和mapDispatchToProps设置以及我的动作和减速器,但每当我尝试输出任何我的映射道具时,我都无法从我已映射状态的道具中获取任何内容。 / p>
我回溯到我的index.js并尝试使用alert(store.getState())和alert(store.getState()。value1)和alert(store.getState(value1))知道value1之后已被派遣,通过我的行动,我的减速机,然后(希望)进入我的商店。我也尝试在mapStateToProps
中使用的prop上使用alert我得到的唯一输出是store.getState()的空白警报和其他选项的未定义。
我不知道我的代码出了什么问题:(
actions / index.js:
export const updateDial1 = (value1, value2) => {
return {
type: 'UPDATE_DIAL_1',
value1,
value2
}
}
减速器/ reducer.js
const update = (state, mutations) => Object.assign({}, state, mutations)
const valuesReducer = (state = [], action) => {
switch (action.type) {
case 'UPDATE_DIAL_1':
{
return [
...state,
{
value1: action.value1,
value2: action.value2,
}
]
}
}
export default valuesReducer
组件/ component.js
(从组件中取出)
// use this to apply values from redux store to local props
const mapStateToProps = state => ({
valuesReducer: state
})
// use this to send changes to the Redux store
const mapDispatchToProps = {
updateDialLine1: actions.updateDial1
}
和export default connect(mapStateToProps, mapDispatchToProps)(CustomComponent)
带存储声明的index.js :( console.log返回一个空数组)
import React, { Component } from 'react';
import { Root } from './navigator/router';
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import valuesReducer from './reducers/dials'
let store = createStore(valuesReducer)
export default class App extends Component {
render() {
// setTimeout(() => {console.log(store)}, 15000)
return (
<Provider store={store}>
<Root />
</Provider>
);
}
}
答案 0 :(得分:1)
在reducer代码示例中,您将array []直接分配给state对象。您应该将reducer代码更改为以下内容:
const valuesReducer = (state = {}, action) => {
switch (action.type) {
case 'UPDATE_DIAL_1':
{
return {
...state,
{
value1: action.value1,
value2: action.value2,
}
}
}
}
请注意在reducer中使用{}而不是[]。
如果您需要在状态对象中使用数组,则将其添加为对象属性:
const valuesReducer = (state = {myArray:[ ]}, action) => {return state}