admin管理员组文章数量:1323342
I was wondering if there was a way to conditionally return state values in mapStateToProps given prop information. See below for some sample code. I am getting some unexpected parsing errors. Is there a way to do something like this? Thanks.
const mapStateToProps = (state, ownProps) => (
if (ownProps.name === "alpha") {
return {
data: state.alpha.data
}
} else if (ownProps.name === "beta") {
return {
data: state.beta.data
}
} else {
return null;
}
);
I was wondering if there was a way to conditionally return state values in mapStateToProps given prop information. See below for some sample code. I am getting some unexpected parsing errors. Is there a way to do something like this? Thanks.
const mapStateToProps = (state, ownProps) => (
if (ownProps.name === "alpha") {
return {
data: state.alpha.data
}
} else if (ownProps.name === "beta") {
return {
data: state.beta.data
}
} else {
return null;
}
);
Share
Improve this question
asked Jul 3, 2018 at 16:58
JimmyJimmy
3,88016 gold badges50 silver badges111 bronze badges
2
- 2 Curly braces for block scope... – Emissary Commented Jul 3, 2018 at 17:06
-
It's most likely just
(
instead of{
as your function body it plains about.const mapStateToProps = (state, ownProps) => { ... };
– Tholle Commented Jul 3, 2018 at 17:09
3 Answers
Reset to default 4You can make use of JavaScript's switch
like this:
const mapStateToProps = (state, ownProps) => {
switch (ownProps.name) {
case "alpha":
return {
data: state.alpha.data
};
case "beta":
return {
data: state.beta.data
};
default:
return null;
}
};
NOTE: The issue with your code is that you are using (
instead of {
in the block scope
of the functions' body.
I would suggest using the selector pattern instead of inserting logic directly.
selectorName(state, name) {
if (name === 'alpha') return state.alpha.data
else if (name === 'beta') return state.beta.data
else return null
}
Then in mapStateToProps:
const mapStateToProps = (state, ownProps) => {
return { data: selectorName(state, ownProps.name) }
}
It helps to reduce potential mistakes and also makes unit testing easier. As an added bonus the data prop will not be null instead of the entire props.
Yes, you can, you just need to write it as a normal function with curly braces instead of parentheses for an immediate return expression.
本文标签: javascriptIf then statements in mapStateToPropsStack Overflow
版权声明:本文标题:javascript - If then statements in mapStateToProps - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742134211a2422297.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论