有条件地渲染反应组件

时间:2020-07-07 22:56:19

标签: javascript reactjs redux

我无法弄清楚为什么我的73个单元测试中只有一个失败了

            sendToSwiftAction = (
                <Button
                    text={buttonText}
                    buttonType="primary"
                    onClick={this.toggleModal}
                    disabled={
                        !canSendToSwift || swiftCommitEnabled
                            ? sendToSwiftStatus !== 'NOT_SENT'
                            : sendToSwiftStatus === 'COMPLETED'
                    }

在我的单元测试中,!canSendToSwift似乎以假的方式返回了

        const btn = render(null, { permissions: [] }).find('Button');

        expect(btn.prop('disabled')).toBeTruthy();
    });

在我添加切换swiftCommitEnabled之前,测试通过得很好。真流量:假流量逻辑。只是!canSendToSwift || sendToSwiftStatus!=='NOT_SENT'传递时。我想念一些简单的东西吗?预先感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

JavaScript将首先计算二进制表达式(||),然后是三进制表达式(?:)。您的代码如下:

const condition = !canSendToSwift || swiftCommitEnabled
const disabled = condition
  ? sendToSwiftStatus !== 'NOT_SENT'
  : sendToSwiftStatus === 'COMPLETED'

或者在纯二进制逻辑运算中更容易理解:

const condition = !canSendToSwift || swiftCommitEnabled
const case1 = sendToSwiftStatus !== 'NOT_SENT'
const case2 = sendToSwiftStatus === 'COMPLETED'
const disabled = (condition && case1) || (!condition && case2)