【问题标题】:why history.goback() doesn't work with one click in react?为什么 history.goback() 不能一键响应?
【发布时间】:2021-08-19 05:50:10
【问题描述】:

我将历史记录作为道具从父组件发送到子组件,当我使用 history.goback() 时,它无法单击一次,需要双击。 例如,我在主页中,然后转到具有 MainMenu.js 组件的第一页,当我单击调用 history.goback() 的按钮时,我需要双击它才能转到主页。问题是什么? 我的 MainMenu.js:

export default function MainMenu (props) {

    const { history} = props;
    
    const handleBack = () => {
        history.goBack();
    }

    


    return (
        <React.Fragment>
            <div className="main-menu-header">
              <div  mr-2 ml-1" onClick={handleBack}>
                            <svg className="float-right" style={{marginRight: -15}} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                                <path fill="none" d="M24 0H0v24h24z" opacity="0.87"/>
                                <path  d="M6.616 2.99a1.249 1.249 0 0 1 1.77 0L16.7 11.3a1 1 0 0 1 0 1.41l-8.31 8.31a1.252 1.252 0 1 1-1.77-1.77L13.856 12l-7.25-7.25a1.246 1.246 0 0 1 .01-1.76z" transform="translate(0.764)"/>
                            </svg>

                        </div>
                           
            </div>

        </React.Fragment>
    )
}

这就是我在其他组件中调用该组件的方式:

<MainMenu  history={props.history} />

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我实际上以这种方式解决了我的问题。我不确定这是否是一个好的答案,但它解决了我的问题!

    export default function MainMenu (props) {
    
        const { history} = props;
    
        useEffect(() => {
            if(history.action === 'POP'){
                history.goBack();
            }
    
        }, [history.action])
        
        const handleBack = () => {
            history.goBack();
        }
    
        
    
    
        return (
            <React.Fragment>
                <div className="main-menu-header">
                  <div  mr-2 ml-1" onClick={handleBack}>
                                <svg className="float-right" style={{marginRight: -15}} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                                    <path fill="none" d="M24 0H0v24h24z" opacity="0.87"/>
                                    <path  d="M6.616 2.99a1.249 1.249 0 0 1 1.77 0L16.7 11.3a1 1 0 0 1 0 1.41l-8.31 8.31a1.252 1.252 0 1 1-1.77-1.77L13.856 12l-7.25-7.25a1.246 1.246 0 0 1 .01-1.76z" transform="translate(0.764)"/>
                                </svg>
    
                            </div>
                               
                </div>
    
            </React.Fragment>
        )
    }
    
    

    保证页面会切换到上一页。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      相关资源
      最近更新 更多