javascript - React JS,整个 react 组件渲染两次
问题描述
下面的 API 调用从服务器获取数据 2 次,导致我的反应组件向 DOM 呈现 2 次,
我怎样才能防止这种行为?我希望我可能需要使用 await 功能
export default function SimpleCard() {
const [posts,setPosts] = useState([]);
useEffect(()=>{
let endpoint = '/api/post/';
apiService(endpoint).then(data=>setPosts(data))
},[]);
return (
<Grid >
{console.log(posts)}
</Grid>
);
}
API.SERVICE.JS
import { CSRF_TOKEN } from "./csrf_token.js"
function handleResponse(response) {
if (response.status === 204) {
return '';
} else if (response.status === 404) {
return null;
} else {
return response.json();
}
}
function apiService(endpoint, method, data) {
// D.R.Y. code to make HTTP requests to the REST API backend using fetch
const config = {
method: method || "GET",
body: data !== undefined ? JSON.stringify(data) : null,
headers: {
'content-type': 'application/json',
'X-CSRFTOKEN': CSRF_TOKEN
}
};
return fetch(endpoint, config)
.then(handleResponse)
.catch(error => console.log(error))
}
export { apiService };
解决方案
上面的组件('<SimpleCard/>')
被父组件调用了 2 次。
不小心我('<SimpleCard/>')
在父组件中列出了。并且反应路由器初始页面是('<SimpleCard/>')
它本身,当我('<SimpleCard/>')
从主要功能中删除它时它工作正常。
function Base() {
return (
<React.Fragment>
<ButtonAppBar/>
<SimpleCard/>
<Route exact path="/" component={SimpleCard}/>
<Route exact path="/profile" component={Profile}/>
<Route exact path="/settings" component={Settings}/>
<Route exact path="/register" component={Register}/>
</React.Fragment>
)
}
export default Base
推荐阅读
- kubernetes-ingress - 从 Ingressgateway 重试
- python - 加快向前看,落后于 pandas DataFrame 中的时间序列搜索
- lua - Lua:如何通过将字符串列入黑名单来阻止 io 库?和沙盒困境
- matlab - Matlab欧拉法
- maven - docker multistage spring boot build pom + 内部依赖
- javascript - 有什么方法可以告诉 Flow getElementById() 返回的 HTMLElement 不能为空?
- c++ - 多次打印出整个数组
- javascript - 使用 Grid fs 在 mongo 数据库中存储数千个图像文件,这是个好主意吗?
- python - 计算字符串中的子字符串,不包括一个字符串
- apache - 如何在 apache 上模拟 500 http 错误