Reactjs 对未提取的数据作出反应错误。丑陋的代码和空指针。怎么办?
我有一个React代码,需要从API获取一些数据,将其放在redux存储中,然后用这些数据呈现一个列表。这就是我所做的Reactjs 对未提取的数据作出反应错误。丑陋的代码和空指针。怎么办?,reactjs,react-native,redux,Reactjs,React Native,Redux,我有一个React代码,需要从API获取一些数据,将其放在redux存储中,然后用这些数据呈现一个列表。这就是我所做的 constructor(props) { super(props); this.state = { isLoading: false, }; } componentDidMount() { this.setState({ isLoading: true }); this.loadData(); } load
constructor(props) {
super(props);
this.state = {
isLoading: false,
};
}
componentDidMount() {
this.setState({ isLoading: true });
this.loadData();
}
loadData = async () => {
try {
API.getList()
.then(data => {
this.updateState(data);
})
.then(data => this.setState({ isLoading: false }))
.catch(function(error) {
console.log(error.message);
});
} catch (e) {}
};
updateState = async (data) => {
if (data != null) {
await this.props.mainActions.receiveData(data);
}
};
render() {
const { isLoading } = this.state;
if (isLoading) {
return <p>Loading ...</p>;
}
let items = [];
if (this.props.items.data !== undefined) {
items = this.props.items.data.stadiums;
}
return <MyList items={items} />;
}
}
问题是,当我第一次尝试获取this.props.items时,它还没有定义
所以我需要把这个丑陋的,如果不打破我的代码
对于这个问题,有什么更优雅的解决方案 好的。只需将componentDidMount更改为componentWillMount 我假设在这里使用ES6: 我将为MyList组件中的项目设置defaultProp
export class MyList extends Component {
...
static defaultProps = {
items: []
}
...
}
这样,如果在呈现方法中将项作为未定义项传递并映射到项上,则会生成一个空数组,该数组是有效的jsx,jsx不会呈现未定义项或null,因此可以在返回语句中包含条件 不要编写if语句,而是执行以下操作:
return (
{
this.props.items.data &&
this.props.items.data.stadiums &&
<Mylist
items={this.props.items.data.stadiums}
/>
}
);
我会说,做些有用的事,然后再弄清楚优雅,除非你在做一些反模式的事情。它正在工作,但在这种情况下似乎不是避免空指针的正确方法。我可以做些什么来使React在生命周期中保持平稳。我想这是我的主要问题。