我有一个react / Redux应用程序。问题是我想在组件状态下渲染元素列表,并且当执行render方法并且我不能使用它时,该列表始终为空。
此元素来自API调用。
这是我的组件:
class PeopleView extends Component {
static propTypes = {
people: PropTypes.array,
view: PropTypes.string
}
static stateToProps = state => ({
people: state.properties.items || [],
sortedPeople: sortBy(state.people.items || [], 'birthday'),
})
constructor(props) {
super(props);
const { people } = props;
const sortedPeople = sortBy(people, 'birthday');
this.state = {
people: people,
sortedPeople: sortedPeople,
collapsed: true
};
}
toggleCollapsed = (e) => {
this.setState({collapsed: !this.state.collapsed});
}
deleteHandler = (id) => {
console.log("Person Id", id)
}
render() {
// THIS IS EMPTY: this.state.people = []
// THIS IS NOT EMPTY: this.props.people = [{...}, {...}, {...}, ...]
const sortedPeople = sortBy(this.props.people, 'createdAt');
const sortedPeopleElements = this.props.sortedPeople.map((p, i) => {
return <li key={p.id}>
<Person index={i} id={p.id} name={p.name} onDelete={this.deleteHandler} />
</li>
});
return (
<div>
<ul>
{sortedPeopleElements}
</ul>
</div>
);
}
}
export default connect(PeopleView);
处于状态的人员在render方法中始终为空,但是props中的人员列表始终可以。为什么会这样?
如何设置可处理渲染的状态并开始从此列表中删除人员?
答案 0 :(得分:0)
您的代码通常存在一些问题。
this.state.people
仅在构造函数中根据this.props.people
的值进行一次初始化,如果您未传入值,则默认值为undefined
。请注意,您没有在this.state.people
方法中的任何地方使用render
。stateToProps
成为组件类的静态方法。通常,它是该功能的顶层(或文件范围)。让我知道是否可以进一步阐明我的答案。
答案 1 :(得分:0)
在您的构造函数中:
constructor(props) {
super(props);
/* Remove { } this brackets from the const variable and also you need props.people not props in it */
const people = props.people;
const sortedPeople = sortBy(people, 'birthday');
this.state = {
people: people,
sortedPeople: sortedPeople,
collapsed: true
};
}