react-router重定向不按预期工作

问题描述 投票:0回答:1

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

我的代码:

//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);
reactjs react-router material-ui
1个回答
1
投票

必须渲染Redirect,但现在你只需从你的点击中返回它。你必须在你的点击上设置一个定义的状态,这将有条件地渲染你的Redirect。布尔值将完成这项工作。

© www.soinside.com 2019 - 2024. All rights reserved.