Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何重构我的arrow函数以使用if语句?_Javascript_Reactjs - Fatal编程技术网

Javascript 如何重构我的arrow函数以使用if语句?

Javascript 如何重构我的arrow函数以使用if语句?,javascript,reactjs,Javascript,Reactjs,我有以下箭头功能: handleTest = () => { this.setState({ test: {a: true}}) } handleTest1 = () => { this.setState({ test1: {a: false}}) } 我在组件中这样称呼它们: this.props.handleTest(); this.props.handleTest1(); 但我想要这样的东西: handleTest

我有以下箭头功能:

handleTest = () => {
        this.setState({ test: {a: true}})
    }
    handleTest1 = () => {
        this.setState({ test1: {a: false}})
    }
我在组件中这样称呼它们:

this.props.handleTest();

this.props.handleTest1();
但我想要这样的东西:

handleTest = (a) => {
    if(a == 'test'){
         this.setState({ a: true })
    }
    else if(a == 'test1'){
        this.setState({ a: false })
    }
} 
然后像这样调用该函数,例如:

this.props.handleTest("test");
我该怎么做


多谢各位

如果在状态逻辑中只有两种可能性,那么可以使用三元语句

//正在通过道具的箭头函数
handleTest=(条件=未定义)=>{
this.setState({a:Boolean(condition)});
}
//召唤
const{handleTest}=this.props;
handleTest(“测试”);//真的
handleTest();//假的
handleTest=(a=false)=>{
让temp=a==‘测试’
this.setState({a:temp})

}
您面临的问题是什么?你已经给出了解决方案!到底是什么问题?是的,你在积极地做这件事,
handleTest=(a)=>{this.setState({a:a=='test'})}
?它不跟踪未定义的,如果这是您也想知道的。否,因为如果
条件
已经是一个表达式,我想使用state。所以你可以只做
{a:condition}
或者
{a:Boolean(condition)}