我在api调用之后尝试通过将有效负载与初始状态Map()合并来尝试更新我的redux存储。我可以在mapStateToProps中使用点表示法访问状态属性,但是当尝试调用state.get(' prop')时,该值是未定义的。
actions.js
export function loadPackages() {
return function(dispatch) {
return PackageApi.getAllPackages().then(packages => {
dispatch(loadPackagesSuccess(packages));
}).catch(error => {
throw(error);
});
};
}
export function loadPackagesSuccess(packages) {
return {
type: 'LOAD_PACKAGES_SUCCESS',
packages
}
}
reducer.js
const reducer = (state = Map(), action) => {
switch (action.type) {
case 'LOAD_PACKAGES_SUCCESS':
return update(state, {$merge: action.packages});
default:
return state;
}
}
export default reducer;
Packages.jsx
const mapStateToProps = (state) => {
console.log(state.results); // (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
return {
state,
packages: state.get('results') // undefined
};
}
修改
reducer.js
const initialState = Map({
packages: {
totalCount: null,
results: List(),
dir: null,
totalPages: null,
limit: null,
sort: null,
page: null
}
});
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'LOAD_PACKAGES_SUCCESS':
return state.set('packages', fromJS(action.packages));
default:
return state;
}
}
Packages.jsx
export class Packages extends React.Component {
componentDidMount() {
this.props.dispatch(loadPackages(this.props.state));
}
render() {
return (
<div className="col-lg-12">
{this.props.results ?
<PackageList allPackages={this.props.results} /> :
<h3>No Packages Available</h3>}
</div>
);
}
};
const mapStateToProps = (state) => {
console.log(state.getIn(['packages','results']));
/* Doesn't print the actual value of results but shows the
immutable structure: List {size: 10, _origin: 0, _capacity: 10,
_level: 5, _root: null, …} */
return {
packages: state.get('packages'),
results: state.getIn(['packages','results'])
};
}
PackageList.jsx
const PackageList = ({allPackages}) => {
const packageItems = allPackages.map(pkg =>
<li key={pkg.get('id')}>{pkg.get('packageName')}</li>
);
return (
<ul className="packages">
{packageItems}
</ul>
);
};
答案 0 :(得分:1)
如果状态中的结构错误,则在reducer中存在问题。
替换为:return update(state, {$merge: action.packages});
这样:return state.set('packages', Immutable.fromJs(action.packages));
现在你使用来自https://reactjs.org/docs/update.html的vanilla js immutable数据变异助手,它返回新的基础JS对象/数组等,并且与Immutable.Js库无关,你尝试在裸JS对象上使用Immutable.js方法