react-router重定向无法按预期工作 [英] react-router redirect not working as expected

查看:56
本文介绍了react-router重定向无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用最新版本的create-react-app,mobx-react,material-ui和react-router.当我尝试使用 Redirect 组件重定向到其他组件时,它不起作用.然后我按照这个 answer ,问题仍然存在.

I am using latest version of create-react-app, mobx-react, material-ui and react-router . When I tried to redirect to other component using Redirect component it doesn't work. Then I followed this answer , still the problem persists.

我的代码:

//App.js
// other imports
import { withStyles } from '@material-ui/core/styles';
import Cart from "./stores/Cart";


const cart_counter = new Cart();


class App extends Component {
    render() {
        return (
            <Router>
                <React.Fragment>
                    <Route path="/" exact render={(props) => <Index {...props} cart_counter={cart_counter}/>} />
                    <Route path="/product/:slug" render={(props) => <Product {...props} cart_counter={cart_counter}/>} />
                </React.Fragment>
            </Router>
        );
    }
}

export default App;


// Index.js
class IndexComponent extends React.Component {
   moveToProduct(slug) {
        return <Redirect push to={"/product/" + slug} />;
    }
   render() {
        return (
          <Grid item xs={6} sm={3} key={product.id}>
                    <Card onClick={() => {this.moveToProduct(product.slug)}}>
           </Grid>
       )}
   const Index = withRouter(observer(IndexComponent));

   export default withStyles(styles)(Index);

推荐答案

必须呈现 Redirect ,但是现在您只需单击鼠标即可将其返回.您必须在点击时设置一个已定义的状态,这将有条件地呈现您的 Redirect .一个布尔值将完成这项工作.

A Redirect must be rendered but right now you just return it from your click. You have to set a defined state on your click which will conditionally render your Redirect. A boolean will do the job.

这篇关于react-router重定向无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆