我在获取一些数据时遇到了一些麻烦。在componentWillReceiveProps,我必须接收一个object widgets,但我发现object widgets包含另一个object widgets,我必须通过widgets.widgets访问它。
期望值:widgets: { value1: 10, value2: 20, value3: 30 }
实际值:widgets: { widgets: { value1: 10, value2: 20, value3: 30 } }
我知道这样做是可能的(但我认为这很丑陋):
componentWillReceiveProps({ widgets }) {
if (widgets !== this.props.widgets) {
this.setState({ widgets: widgets.widgets });
}
}任何帮助都将不胜感激!
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as widgetsActions from '../js/actions/widgetsActions';
import Dashboard from './dashboard/Dashboard';
import style from './App.scss';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
widgets: this.props.widgets,
};
}
componentWillMount() {
if (JSON.stringify(this.state.widgets) === JSON.stringify({})) {
this.props.loadWidgets();
}
}
componentWillReceiveProps({ widgets }) {
if (widgets !== this.props.widgets) {
this.setState({ widgets });
}
}
render() {
return (
<div className={style.app}>
{(JSON.stringify(this.state.widgets) !== JSON.stringify({})) &&
<div>
<Dashboard widgets={this.state.widgets} />
</div>
}
</div>
);
}
}
App.propTypes = {
loadWidgets: PropTypes.func.isRequired,
widgets: PropTypes.shape({
value1: PropTypes.number,
value2: PropTypes.number,
value3: PropTypes.number,
}).isRequired,
};
const mapStateToProps = state => (
{
widgets: state.widgets,
}
);
const mapDispatchToProps = dispatch => (
{
loadWidgets: () => dispatch(widgetsActions.loadWidgets()),
}
);
export default connect(mapStateToProps, mapDispatchToProps)(App);发布于 2017-07-10 08:25:54
我猜是你的减速器设置出了问题。Redux文档的Structuring Reducers - Using combineReducers部分描述了为什么会发生这种情况的几个原因,这通常是对combineReducers和切片缩减器如何协同工作来定义状态结构的误解。
https://stackoverflow.com/questions/45002128
复制相似问题