我正在使用 React redux 构建一个可以增加或减少的数字的 div。
问题是一切看上去都不错 但浏览器上没有结果
reducer->index.js:
import { combineReducers } from 'redux'
const sumReducer = (sum = 0, action) => {
if (action.type === 'ADD' || action.type === 'SUB') {
let x = action.payload;
return x;
}
return sum;
}
export default combineReducers({
sum: sumReducer
});
**action-> index.js**
export const add = (sum) => {
return {
type: 'ADD',
payload: sum + 1
}
}
export const sub = (sum) => {
return {
type: 'SUB',
payload: sum - 1
}
}
我的组件是:upDownSum.js
import React from 'react'
import { connect } from 'react-redux'
import { add, sub } from '../action'
class UpDownSum extends React.Component {
render() {
console.log(this.props);
console.log("ghj");
return (
<div key="1">
<button onClick={() => sub(this.props.sum)}>-</button>
<div>{this.props.sum}</div>
<button onClick={() => add(this.props.sum)}>+</button>
</div>
)
}
}
const MapStateToProps = (state) => {
return {
sum: state.sum
}
}
export default connect(MapStateToProps, {add: add ,sub: sub})(UpDownSum);
app.js 导入'./App.css'; 从 './upDownSum' 导入 UpDownSum
function App() {
return (
<UpDownSum/>
);
}
export default App;
谢谢!
您将调度映射到 props,这意味着要调度操作,您需要确保使用
props
而不仅仅是导入的操作:
return (
<div>
<button onClick={() => this.props.sub(this.props.sum)}>-</button>
<div>{this.props.sum}</div>
<button onClick={() => this.props.add(this.props.sum)}>+</button>
</div>
)