【发布时间】:2018-08-21 13:19:30
【问题描述】:
我只是想学习使用 redux,我有一个非常简单的计数器列表组件,它有一个子计数器组件的列表。
我在计数器上有一个 onIncrement 操作,我想在单击时增加计数。
当我单击增量时,它会更新父状态,但子计数器不会更新。如果我浏览然后返回列表,它确实呈现正确,这在我看来意味着状态已更新。
这是我的代码:
计数器组件
import React, { Component } from "react";
import { connect } from 'react-redux';
import { incrementCounter } from '../../actions/counterActions';
import PropTypes from 'prop-types';
class Counter extends Component {
render() {
return <div className="m-2">
<b>{this.props.counter.count}</b>
<button className="btn btn btn-secondary btn-sm m-2" onClick={() => { this.onIncrement(this.props.counter) }}>Increment</button>
</div>;
}
onIncrement(counter) {
this.props.incrementCounter(counter);
}
}
const mapStateToProps = state => ({
})
Counter.propTypes = {
incrementCounter: PropTypes.func.isRequired,
}
export default connect(mapStateToProps, { incrementCounter })(Counter);
计数器列表组件
import React, { Component } from "react";
import { RouteComponentProps } from "react-router";
import { CounterContext } from "../../contexts/context.js";
import Counter from "./Counter";
import { NewItem } from "./NewItem";
import ItemContainer from "../layout/ItemContainer";
import { connect } from 'react-redux';
import { getCounters } from '../../actions/counterActions';
import PropTypes from 'prop-types';
class CounterList extends Component {
componentWillMount() {
if (this.props.counters.length == 0) {
this.props.getCounters();
}
}
render() {
const counterItems = this.props.counters.map(counter => <Counter key={counter.id} counter={counter} />);
return <div>{ counterItems }</div>;
}
}
const mapStateToProps = state => ({
counters: state.counters.items
})
CounterList.propTypes = {
getCounters: PropTypes.func.isRequired,
counters: PropTypes.array.isRequired
}
export default connect(mapStateToProps, { getCounters })(CounterList);
反制措施
import { GET_COUNTERS, INCREMENT_COUNTERS } from '../actions/types';
export const getCounters = () => dispatch => {
const counters = [{ id: 1, count: 4 }, { id: 2, count: 3 }, { id: 3, count: 0 }];
// this could be API call to get initial counters
console.log('In GetCounters', GET_COUNTERS);
return dispatch({
type: GET_COUNTERS,
payload: counters
})
}
export const incrementCounter = (counter) => dispatch => {
// this could be API call to get initial counters
counter.count++;
return dispatch({
type: INCREMENT_COUNTERS,
payload: counter
})
}
计数器减速器
import { GET_COUNTERS, INCREMENT_COUNTERS } from '../actions/types';
const initialState = {
items: []
}
export default function (state = initialState, action) {
console.log(action.type);
switch (action.type){
case GET_COUNTERS:
return {
...state,
items: action.payload
};
case INCREMENT_COUNTERS:
var counter = action.payload;
const counters = [...state.items];
const index = counters.findIndex(x => x.id == counter.id);
counters[index] = counter;
return {
...state,
items: counters
};
default:
return state;
}
}
【问题讨论】:
标签: javascript reactjs redux