首页 > 解决方案 > React Router 历史在表单提交后推送到路径但不渲染组件

问题描述

每次我使用 axios 提交表单时,都会history.push更新浏览器中的路径,但不会渲染组件。但是,当我使用 BrowserRouter 时,它可以正常工作,但显然它不支持历史记录。

应用程序.js

import React from 'react';
import {Router, Route, Switch, BrowserRouter, withRouter} from 'react-router-dom';
import {history} from "./helpers";

import Layout from './containers/Layout'
import AllProductsList from "./containers/AllProducts";
import ProductAnalytics from "./containers/ProductAnalytics";


function App() {
  return (
    <>
        <Router history={history}>
            <Layout>
                <Switch>
                    <Route path="/sell/allproducts" component={withRouter(AllProductsList)} />
                    <Route path="/sell/analytics/:product_id" component={withRouter(ProductAnalytics)} />
                </Switch>
            </Layout>
        </Router>
    </>
  );
}

export default App;

布局.js

import React from "react";
import Sidebar2 from "../components/sidebar2";
import Navbar2 from "../components/navbar2";
import Footer from "../components/Footer";
import {withRouter} from 'react-router-dom';


const Layout = ({children}) => {
    return(
        <div id="wrapper">
            <Navbar2 />
            <Sidebar2 />
            <div className="content-page">
                <div className="content">
                    {children}
                </div>
            </div>
            <Footer />
        </div>
    );
};

export default withRouter(Layout);

所有产品.js

const ProductCreateModal = (props) => {

    const [loading, setLoading] = useState(false)
    const [error, setError] = useState(null);

    const {
        buttonLabel='Add New Product',
        className
    } = props;

    const [modal, setModal] = useState(false);
    const toggle = () => setModal(!modal);

    const [productName, setProductName] = useState(null)
    const [productPrice, setProductPrice] = useState(null)
    const [productImage, setProductImage] = useState(null)

    function handleSubmit(e) {
        e.preventDefault();
        setLoading(true);
        console.log(productName)
        console.log(productPrice)
        console.log(productImage)

        const formData = new FormData()
        formData.append("name", productName)
        formData.append("price", productPrice)
        if(productImage) formData.append("image", productImage)
        formData.append("status", "ACTIVE")
        console.log(formData)
        axios
            .post(api.product.create, formData, {
                headers: {
                    "Content-Type": "multipart/form-data"
                }
            })
            .then(res => {
                console.log(res)
                setLoading(false);
                history.push('/sell/allproducts')
            })
            .catch(err => {
                console.log(err)
                setLoading(false);
                setError(err.message || err)
            })
    }

        return(
            <>
                <Button color="success" className="waves-effect waves-light mb-3" onClick={toggle}><i className="mdi mdi-cloud-upload mr-1"/>{buttonLabel}</Button>
                <Modal isOpen={modal} toggle={toggle} className={className}>
                    <ModalHeader toggle={toggle}>Add New Product</ModalHeader>
                    <ModalBody>
                        <Form onSubmit={handleSubmit}>
                            <FormGroup>
                                <Label for="exampleEmail">Name</Label>
                                <Input
                                    type="text"
                                    name="name"
                                    id="exampleEmail"
                                    placeholder="Product name"
                                    value={productName}
                                    onChange={e => setProductName(e.target.value)}
                                />
                            </FormGroup>
                            <FormGroup>
                                <Label for="examplePassword">Price</Label>
                                <Input
                                    type="number"
                                    min="1"
                                    step="any"
                                    name="Price"
                                    id="examplePassword"
                                    placeholder="Product Price"
                                    value={productPrice}
                                    onChange={e => setProductPrice(e.target.value)}
                                />
                            </FormGroup>
                            <FormGroup>
                                <Label for="exampleText">Description</Label>
                                <Input
                                    type="textarea"
                                    name="Description"
                                    id="exampleText"
                                />
                            </FormGroup>
                            <FormGroup>
                                <Label for="exampleFile">Image</Label>
                                <Input
                                    type="file"
                                    name="file"
                                    id="exampleFile"
                                    onChange={e => setProductImage(e.target.files[0])}
                                />
                                <FormText color="muted">
                                    This is some placeholder block-level help text for the above input.
                                    It's a bit lighter and easily wraps to a new line.
                                </FormText>
                            </FormGroup>
                            <Button color='success' block>Submit</Button>
                        </Form>
                    </ModalBody>
                </Modal>
            </>
        )
};

助手/history.js

import {createBrowserHistory} from "history";
export const history = createBrowserHistory();

助手/index.js

export * from "./history";

如何使用 Router 和history.push

标签: reactjsreact-routerreact-router-dombrowser-historyhistory.js

解决方案


推荐阅读