首页 > 解决方案 > ReactJS:条件为真后如何进入下一页?

问题描述

满足条件后如何自动跳转到下一页?

handleSubmit = event => {
     event.preventDefault();
        const { data } = this.state
        const tabletopModel = data['token']
        const newData = tabletopModel ? tabletopModel.all() : null
        console.log('log for newdata', newData)


        var c = 0;

        if (newData == null) {
            console.log('null')
        }
        else {

            for (var i = 0; i < newData.length; i++) {
                if (newData[i].ID == this.input.value) {
                    c++;
                    //console.log('i', i);
                }

            }
            if (c > 0)
            alert('Your username is: ' + this.input.value);
            //GO TO NEXT PAGE
            else { 
                alert('Invalid login');
            }
        }


    };

这是一个按钮存在的代码,点击它会运行这部分

这是正确的还是有更好的解决方案?

标签: reactjs

解决方案


this.props.history.push如果您在一个类组件中或者它是一个功能组件,您可以使用props.history.push,您还可以将状态传递给您要重定向到的页面,例如:

this.props.history.push({
  pathname: '/next-page',
  state: { from: "prev-page" }
})

通过的状态将存储在props.location.state下一页中,

你也可以替换这个:

for (var i = 0; i < newData.length; i++) {
    if (newData[i].ID == this.input.value) {
        c++;
        //console.log('i', i);
    }
}

有了这个:

if(newData.some(currentValue => currentValue.ID === this.input.value)) {
    c++;
    //console.log('i', i);
}

推荐阅读