在 react 中声明默认 props 的正确方法是什么,这样当我在使用 redux 异步分配的 prop 上调用 map 时,我不会收到未定义的错误?现在,使用以下语法,我在尝试分配 trans_filter 时收到错误消息,因为在对渲染的初始调用中数据未定义。
class ContainerComponent extends React.Component {
static defaultProps = {
searchProps: {
data: []
}
};
constructor(props) {
super(props);
}
render(){
let trans_filter = JSON.parse(JSON.stringify(this.props.searchProps.data));
}
}
const mapStateToProps = (state) => ({
searchProps: state.searchProps
});
export default connect(mapStateToProps, {getTransactionsAll})(ContainerComponent);
最佳答案
以下是在使用 ES6 类语法创建 ReactJS 组件时如何声明默认 Prop :
class ContainerComponent extends React.Component {
constructor(props) {
super(props);
}
render(){
let trans_filter = JSON.parse(JSON.stringify(this.props.searchProps.data));
}
}
ContainerComponent.defaultProps = {
searchProps: {
data: []
}
};
export default ContainerComponent;
此外,还有另一种语法用于声明defaultProps
。 这是一个快捷方式,但只有当您的构建打开了 ES7 属性初始化器时它才会起作用。我认为这就是它对您不起作用的原因,因为我认为您的语法没有问题:
class ContainerComponent extends React.Component {
static defaultProps = {
searchProps: {
data: []
}
};
constructor(props) {
super(props);
}
render() {
let trans_filter = JSON.parse(JSON.stringify(this.props.searchProps.data));
}
}
export default ContainerComponent;
编辑:在你分享了你的mapStateToProps
之后,是的,它与Redux有关!
问题是由您的 reducer
引起的。您必须声明 initial state shape此外,您必须在每个 reducer 中指定初始状态。 Redux 将第一次使用 undefined
状态调用我们的 reducer。这是我们返回应用初始状态的机会。
设置初始状态:
const searchPropsInitialState = {
data: []
};
然后,当您操作 searchProps
时,在您的 reducer 中执行:
function yourReducer(state = searchPropsInitialState, action) {
// ... switch or whatever
return state;
}
有关详细信息,请参阅 handling actions in the Redux docs .
关于reactjs - 使用 Redux 时如何声明 ReactJS 默认 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522022/