我有以下代码,但是当显示网页时, this.props.items 没有传递给 Item。当我尝试在 中输出 this.props.items 时console.log
,没有显示任何内容。但是,当页面通过将其保存在代码编辑器中而不是重新加载页面来自动刷新时, this.props.items 被正确传递。
为什么会这样?如果你能告诉我更多关于它的信息,我将不胜感激。
import React, { Component } from 'react';
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { getItems } from '../../actions/items'
class Container extends Component {
static propTypes = {
items: PropTypes.array.isRequired,
getItems: PropTypes.func.isRequired,
}
componentWillMount() {
this.props.getItems();
}
render() {
return (
<Item timetable={this.props.items} />
);
}
}
const mapStateToProps = (state) => ({
items: state.items.items,
});
export default connect(mapStateToProps, { getItems })(Container);
export const getItems = () => (dispatch, getState) => {
axios.get(`${url}/items/`, tokenConfig(getState))
.then(res => {
dispatch({
type: GET_ITEMS,
payload: res.data
})
}).catch(err => console.log(err));
}
最有可能的问题是您的后端 API 响应时间超出了您的预期。检查您从后端 API 获取的数据是否实际存在始终是一个很好的做法,从某种意义上说不是 null/非空。对此最常见的计数器是使用Loader
组件并等待直到从服务器获取整个数据。
class Container extends Component {
static propTypes = {
items: PropTypes.array.isRequired,
getItems: PropTypes.func.isRequired,
}
componentWillMount() {
this.props.getItems();
}
render() {
if (!this.props?.items) return (<p>Loading...</p>); // --> Use a guard clause
return (
<Item timetable={this.props.items} />
);
}
}
请仔细阅读这些参考资料以更清楚地了解我阐述的要点:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句