我刚开始用Redux学习React JS,我认为这是一个非常容易回答的问题。我有以下代码:
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from "redux";
//
//----------------------------------------------------------------------------------------
//
const initialState = {
count: 0
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
case 'RESET':
return { ...state, count: state.count = 0 };
}
}
const store = createStore(reducer);
store.subscribe(() =>
console.log("subscribe log:",store.getState())
)
const Counter = ({ value, onIncrement, onDecrement, onReset }) =>
(
<div>
<h1>{value}</h1>
<button onClick={onIncrement}>+</button>
<button onClick={onReset}>Reset</button>
<button onClick={onDecrement}>-</button>
</div>
);
const render = () => {
ReactDOM.render(
<Counter
value={ store.getState() }
onIncrement={ () => store.dispatch({ type: 'INCREMENT' }) }
onDecrement={ () => store.dispatch({ type: 'DECREMENT'}) }
onReset={ ()=> store.dispatch({ type: 'RESET'}) }
/>,
document.getElementById('root')
);
};
render()
代码执行时,会呈现html,但状态值不会显示在
非常感谢任何帮助 谢谢。
答案 0 :(得分:3)
首先,使用redux时 你的Reducer应该有一个返回初始状态的默认情况
喜欢
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
...state,
count: state.count + 1
}
case 'DECREMENT':
return {
...state,
count: state.count - 1
}
case 'RESET':
return {
...state,
count: state.count = 0
}
default:
return state
}
}
另一个错误是您将对象传递给计数器组件
store.getState() // returns an object
您应该将其更改为
store.getState().count
最后你正在使用一个功能组件(Counter),它没有状态,并且在你的商店状态发生变化时不会重新呈现。
如果要对商店更改做出反应,则必须创建一个类Component,它在componentDidMount生命周期方法中订阅商店,并使用setState方法重新呈现组件。
因此,为了显示更改,您必须在订阅函数中调用render,如
const initialState = {
count: 0
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
...state,
count: state.count + 1
}
case 'DECREMENT':
return {
...state,
count: state.count - 1
}
case 'RESET':
return {
...state,
count: state.count = 0
}
default:
return state
}
}
const store = Redux.createStore(reducer);
const Counter = (props) => {
const { value, onIncrement, onDecrement, onReset } = props;
return (
<div>
<h1>{value}</h1>
<button onClick={onIncrement}>+</button>
<button onClick={onReset}>Reset</button>
<button onClick={onDecrement}>-</button>
</div>
);
}
const render = () => {
ReactDOM.render(
<Counter
value={store.getState().count}
onIncrement={() => store.dispatch({ type : 'INCREMENT' })}
onDecrement={() => store.dispatch({ type : 'DECREMENT' })}
onReset={() => store.dispatch({ type : 'RESET' })}
/>,
document.getElementById('root')
);
};
store.subscribe(() => {
console.log(store.getState());
render();
})
render()
a demo