React-Redux。。如何获取要通过setState传递的redux结果值。我知道这个问题可能以前曾被问过 但是我在这里找到的大多数解决方案都无法解决我的问题。
下面的代码显示JSON文件中的记录
[{"id":"1","firstName":"jmarkatti","lastName":"john"}]
下面的代码显示了如何在render()方法中显示没有map()函数的结果,并且效果很好。
Last Name: {pgs1.items1 && this.props.pgs1.items1[0].lastName}<br />
First Name: {pgs1.items1 && this.props.pgs1.items1[0].lastName}<br />
下面的代码显示了如何使用render()方法中的 map()函数显示结果,该方法也可以正常工作。
{pgs1.items1 && pgs1.items1.map((pg1, i) =>
<li key={pg1.id}>
{pg1.firstName} -- {pg1.lastName}
</li>
)}
现在,我需要在 setState()方法中传递redux结果值,然后发出警报。为此,我有 在下面尝试了以下代码
componentWillMount() {
this.props.dispatch(userActions.getAll_Rec());
this.setState({
lastName: this.props.pgs1.items1 && this.props.pgs1.items1[0].lastName,
firstName: this.props.pgs1.items1 && this.props.pgs1.items1[0].firstName,
});
alert(lastName);
alert(firstName);
}
or
componentWillReceiveProps(props) {
this.setState({
lastName: props.items1[0].lastName,
firstName: props.items1[0].firstName,
});
alert(lastName);
alert(firstName);
}
但是显示错误
ReferenceError:未定义lastName 在Paging1.componentWillMount ,似乎无法正确访问lastName和firstName的JSON文件。
这是Redux代码
import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import {UActions } from '../actions';
class Paging1 extends React.Component {
constructor(props) {
super(props);
this.state = {
id: '',
lastName: '',
firstName: '',
};
}
// componentDidMount() {
componentWillMount() {
this.props.dispatch(userActions.getAll_Rec());
}
/*
i have tried
componentWillMount() {
this.props.dispatch(userActions.getAll_Rec());
this.setState({
lastName: this.props.pgs1.items1 && this.props.pgs1.items1[0].lastName,
firstName: this.props.pgs1.items1 && this.props.pgs1.items1[0].firstName,
});
alert(lastName);
alert(firstName);
}
or
componentWillReceiveProps(props) {
this.setState({
lastName: props.items1[0].lastName,
firstName: props.items1[0].firstName,
});
alert(lastName);
alert(firstName);
}
*/
render() {
const { pg1, pgs1 } = this.props;
return (
<div className="list">
<div className="res">
Last Name: {pgs1.items1 && this.props.pgs1.items1[0].lastName}<br />
First Name: {pgs1.items1 && this.props.pgs1.items1[0].lastName}<br />
</div>
</div>
);
}
}
function mapStateToProps(state) {
const { pgs1} = state;
const { pg1 } = state;
return {
pg1,
pgs1
};
}
const connectedPaging1 = connect(mapStateToProps)(Paging1);
export { connectedPaging1 as Paging1 };
这是Reducer文件
import { userConstants } from '../_constants';
export function pgs1(state = {}, action) {
switch (action.type) {
case userConstants.GETALL_REQUEST:
return {
...state,
loading: true
};
case userConstants.GETALL_SUCCESS:
return {
loading: false,
error: null,
items1: action.pgs1
};
答案 0 :(得分:0)
通过 componentWillReceiveProps()函数传递 redux 结果记录解决了该问题。
谢谢
componentWillReceiveProps(props) {
this.setState({
lastName: props.pgs1.items1 && props.pgs1.items1[0].lastName,
firstName: props.pgs1.items1 && props.pgs1.items1[0].firstName,
});
}