[英]React Route content triggers twice
为什么此警报触发两次?
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { BrowserRouter as Router, Route} from 'react-router-dom'
ReactDOM.render(
<Router>
<Route path="" render={props => {
fetch('some_path').then(response => response.json)
.then(data => {
alert("i show up twice!");
return <p>something</p>
});
</Router>
, document.getElementById('root'));
我想解析querystring,然后相应地传递数据,我注意到该代码运行了两次。 我以一个简单的警报为例。
编辑:我更深入地挖掘了,显然问题不是因为我什么都没退,而是因为我拿东西了。 我更新了示例。
那是因为您没有将任何东西返回给Route组件进行渲染。 尝试这个:
ReactDOM.render(
<Router>
<Route
path=""
render={props => {
fetch("some_path")
.then(response => response.json)
.then(data => {
alert("i show up twice!");
return <p>something</p>;
});
return <p>something</p>;
}}
/>
</Router>,
document.getElementById("root")
);
尽管@Massimiliano暗示了一个答复,但我发布了这个单独的答案,因为我不认为这个答案是完整的。
在原始问题中提供的代码片段中,问题是我试图在渲染组件之前获取数据(我正在考虑将获取的数据作为参数传递给组件)。
正确的方法是渲染组件,然后在react组件的生命周期中使用componentDidMount()
。 在那里,我解析了查询字符串,获取了数据并更新了状态(使用this.setState()
)。
就像文档所说的那样,调用componentDidMount()
会触发重新渲染,但是它首先发生在浏览器渲染页面之前。 因此,即使在幕后,用户也不会将其视为双重渲染。
我没有设法找出为什么我不能在<Route>
获取数据的确切原因,但是我上面描述的流程是满足我需要的正确方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.