reactjs - 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 }
/>
);
}
解决方案
当后续的 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 发生变化),这反过来又会设置状态并发生重新渲染
推荐阅读
- realm - Swift 4.0 和 Xcode 9.4 下的 RLMSupport.swift 编译错误
- cakephp - 如何使用 Cakephp 进行查询连接?
- javascript - 将水平滚动更改为垂直滚动
- python-2.7 - 使用python2内核在GCP的datalab实例中安装apache beam时出错
- r - 如何获得R中组内列之间的差异?
- google-app-engine - 如何知道历史上超出了哪个 appengine 配额
- angular - Angular - 为什么订阅?为什么不直接在组件中使用服务的属性?
- angular - 以角度 4 更改所选链接的颜色
- python - 无法定位元素:python 爬行中的 css 选择器或 xpath
- java - 这是对这种方法进行单元测试的好方法吗?