我的 react-redux 应用程序正在 JSON 中获取单个记录,但该记录是一个数组,因此它看起来像这样(注意 [ ] 括号(:
{"person":[{"PersonID":1,"Name":"John Smith","Gender":0}]}
因此,redux 存储将其显示为 person->0->{"PersonID":1,"Name":"John Smith","Gender":0}。因此,状态显示 person 对象为空:
Name: this.props.person?this.props.person.Name:'object is empty',
我的人页面.js包含如下详细信息页面:
<PersonDetail person={this.props.person} />
详细信息页面包含以下内容:
import React from 'react';
import classnames from 'classnames';
class PersonDetail extends React.Component {
state = {
Name: this.props.person?this.props.person.Name:'',
PersonID: this.props.person?this.props.person.PersonID:null,
loading: false,
done: false
}
componentWillReceiveProps = (nextProps) => {
this.setState({
PersonID: nextProps.person.PersonID,
Name: nextProps.person.Name
});
}
这是我的原始 Redux 状态:
people: [
[
{
PersonID: 51,
Name: 'John Smith',
Gender: 0
}
]
]
Person
是一个 array
,其中包含存在 Name 键的object
,因此您还需要使用 index
,这样写:
this.props.person && this.props.person.length ? this.props.person[0].Name : '';
检查此示例:
var data = {
"person":[
{
"PersonID":1,
"Name":"John Smith",
"Gender":0
}
]
};
console.log('Name: ', data.person[0].Name);
我认为您应该为每个人的数据映射人员详细信息。
在"人员页面"上.js ,
映射如下:
{
this.props.person.map((p)=>{
return (<PersonDetail person={p} />)
})
}
如果我是你,我会做一个这样的 util 函数:
const parsePeople = people => {
if (people instanceof Array) return parsePeople(people.pop())
return people
}
const people = [
[{
PersonID: 51,
Name: 'John Smith',
Gender: 0
}]
]
const person = parsePeople(people)
console.log(person) -> Object
使用递归我们检查 people 是否是 Array
的实例,我们使用返回数组最后一个元素的 people.pop()
再次调用该函数。
你的个人数据上有一个数组...您只能在没有 0 的情况下使用 map 访问它...
例:
componentWillReceiveProps = (nextProps) => {
var PersonID = nextProps.person ? nextProps.person.map(item => { return item.PersonID}) : '';
var Name = nextProps.person ? nextProps.person.map(item => { return item.Name}) : '';
this.setState({
PersonID,
Name
});
}
这是考虑到您只有 1 个 Person 上的数组。
我修好了!这是给出的两个答案的组合:在 PersonPage.js 中,我不得不像这样调用 PersonDetails 对象:
<PersonDetail
person={this.props.person[0]}
/>
这是新的MapStatetoProps:
function mapStateToProps(state, props) {
const { match } = props;
if (match.params.PersonID) {
return {
person: state.people
}
}
感谢那些回答的人。这让我发疯。