使用 Redux 时如何声明 ReactJS 默认道具? [英] How to declare ReactJS default props when using Redux?
问题描述
在反应中声明默认道具的正确方法是什么,以便当我在使用 redux 异步分配的道具上调用 map 时,我不会收到未定义的错误?现在,使用以下语法,我在尝试分配 trans_filter 时遇到错误,因为在初始调用 render 中未定义数据.
What is the right way to declare default props in react so that when I call map on a prop that is asynchronously assigned using redux I do not get an undefined error? Right now, with the following syntax I get an error when trying to assign trans_filter because data is undefined in the initial call to render.
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 组件时声明默认道具的方法:
Here's how you can declare default props when using the ES6 class syntax for creating ReactJS components:
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 属性初始化器时,它才会起作用.我认为这就是它对您不起作用的原因,因为我认为您的语法没有问题:
Additionally, there is another syntax for declaring defaultProps
. This is a shortcut, but it will work only if your build has ES7 property initializers turned on. I assume that's why it doesn't work for you, because I see no issues with your syntax:
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
引起的.您必须声明初始状态形状 以及更多,您必须在每个减速器中指定初始状态.Redux 将第一次以 undefined
状态调用我们的 reducer.这是我们返回应用初始状态的机会.
after you shared your mapStateToProps
, yes, it has something to do with Redux!
The issue is caused by your reducer
. You must declare initial state shape and moreover, you must specify the initial state in each reducer. Redux will call our reducer with an undefined
state for the first time. This is our chance to return the initial state of our app.
设置初始状态:
const searchPropsInitialState = {
data: []
};
然后,在你的 reducer 中操作 searchProps
时:
Then, in your reducer when you manipulate searchProps
do:
function yourReducer(state = searchPropsInitialState, action) {
// ... switch or whatever
return state;
}
有关详细信息,请参阅 Redux 文档中的处理操作一>.
For more details, see handling actions in the Redux docs.
这篇关于使用 Redux 时如何声明 ReactJS 默认道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!