我在尝试使用redux进行编码时遇到了问题。 我基本上试图结合redurs.I紧接着 Getting Started with Redux tutorial,但我似乎有一个完全不同的问题。虽然我理解错误,但我找不到解决方案。
以下是我想要合并的减速机:
const increment = (state = 0, action)=>{
console.log(state,action)
switch (action.type){
case 'INCREMENT':
return state-1;
default:
return state;
}
}
const decrement = (state = 0, action)=>{
console.log(state,action)
switch (action.type){
case 'DECEREMNT':
return state-1;
default:
return state;
}
}
const combineReducers = require('redux').combineReducers;
const counter = combineReducers({
increment,
decrement,
})
module.exports = counter;
如果我执行以下操作,则无问题,
const counter = (state = 0, action)=>{
console.log(state,action)
switch (action.type){
case 'INCREMENT':
return state+1;
case 'DECEREMNT':
return state-1;
default:
return state;
}
}
module.exports = counter
所以我相信在组合减速器时我会遇到一些问题。 以下是我收到的错误:
Uncaught Error: Objects are not valid as a React child (found: object with keys {increment, decrement}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Counter`.
如果相关,我的索引如下:
"use strict";
const React = require('react');
const ReactDOM = require('react-dom');
const createStore = require("redux").createStore
var counter = require("./reducers")
const store = createStore(counter)
console.log("First call",store.getState())
const Counter = ({
value,
increment,
decrement
}) =>(
<div>
<h1>{value}</h1>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
const render = () =>{
console.log("value ",store.getState());
console.log("dispatch action",)
ReactDOM.render(
<Counter value={store.getState()}
increment={()=>{store.dispatch({type:'INCREMENT'})}}
decrement={()=>{store.dispatch({type:'DECREMENT'})}}/>,
document.getElementById('content')
);
}
store.subscribe(render)
render()
我正在努力学习分离减速器。我已经做了很少的项目,但我有一个reducer文件太大导致合并问题。如果我正在采取正确的方法,请告诉我,我们将非常感谢您解决上述问题的任何建议。
更新 我试图独立调用store.dispatch({type:&#39; INCREMENT&#39;}),它确实有效,但会导致浏览器继续增加导致浏览器冻结的值。
以下反应代码正在运作。
var Counter = React.createClass({
render:function(){
console.log(this.props.value)
return <div>
{this.props.value.counter}
<button onClick={this.props.increment}>+</button>
<button onClick={this.props.decrement}>-</button>
</div>
}
});
const render = () =>{
console.log("value ",store.getState());
ReactDOM.render(
<Counter value={store.getState()}
increment={()=>{store.dispatch({type:'INCREMENT'})}}
decrement={()=>{store.dispatch({type:'DECREMENT'})}}/>,
document.getElementById('content')
);
}
store.subscribe(render)
render()
的缩减器