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
Add a ment  | 

3 Answers 3

Reset to default 4

You 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