【问题标题】:react-router redirect not working as expected反应路由器重定向未按预期工作
【发布时间】:2019-08-09 03:19:52
【问题描述】:

我正在使用最新版本的 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】:

    Redirect 必须被渲染,但现在您只需通过点击返回它。您必须在单击时设置一个定义的状态,这将有条件地呈现您的Redirect。布尔值可以完成这项工作。

    【讨论】:

    • 作为替代方案,您可以使用this.props.history.push(/push/${slug}) 进行重定向。
    猜你喜欢
    • 2019-05-27
    • 1970-01-01
    • 2011-08-30
    • 2014-05-02
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    相关资源
    最近更新 更多