首页 > 解决方案 > React-router 使用正则表达式在 URL 更改时重新渲染

问题描述

我有一个这样的应用程序:

function App() {
return (
    <Router>
        <OpNavbar/>
        <Route exact={true} path="/" render={() => (
            <h1>This is the welcome page!</h1>
        )}/>
        <Route path="/([a-z]{3,4})/([a-z]+)list" component={OpTable}/>
    </Router>
    );
}

如果我在“/”中并通过单击指向例如“/pfm/examplelist”的链接来切换路径,反之亦然,它会毫无问题地呈现相应的组件。但是,如果我说“/pfm/examplelist”并切换到“/pfm/anotherlist”,则 url 会更改,但我的组件不会被重新渲染。我认为这是因为旧路径和新路径都匹配我的正则表达式?如何在每次 url 更改时重新渲染我的组件?

这是我的 Table 组件的精简版:

function OpTable(props) {
    const [apiData, setData] = useState([]);
    const [columns, setColumns] = useState([{dataField: "Dummy", text: "Loading, Please Wait..."}]);

    useEffect(() => {
        axios.get(props.match.url)
        .then(response => {
            let res_data = response.data;
            setData(res_data.data);
            setColumns(res_data.columns);
        })
        .catch(error => {
            console.log(error);
        })
    }, [])

    return (
        <BootstrapTable
            keyField="id"
            data={ apiData }
            columns={ columns }
        />
    );
}

标签: reactjsreact-router

解决方案


当后续的 url 调用相同的组件时就是这种情况。如果你想重新渲染,一种方法是在 useEffect 中跟踪你的路径(url)。

 useEffect(() => {
        axios.get(props.match.url)
        .then(response => {
            let res_data = response.data;
            setData(res_data.data);
            setColumns(res_data.columns);
        })
        .catch(error => {
            console.log(error);
        })
    }, [props.location.pathname])

我不是钩子的常规用户(我的语法可能有误)。但是逻辑是调用该组件所需的 api(只要 url 发生变化),这反过来又会设置状态并发生重新渲染


推荐阅读