[英]React JS, entire react component renders two times
The below API call fetches data from server 2 times causing my react components to render 2 time to DOM,下面的 API 调用从服务器获取数据 2 次,导致我的反应组件向 DOM 呈现 2 次,
How can I prevent this behavior?如何防止这种行为? I hope I may need to use await function
我希望我可能需要使用 await function
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 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 };
Above component ('<SimpleCard/>')
was called by the parent component 2 times.上面的组件
('<SimpleCard/>')
被父组件调用了 2 次。
Accidently I listed ('<SimpleCard/>')
in parent component.不小心我在父组件中列出了
('<SimpleCard/>')
。 And react router initial page was ('<SimpleCard/>')
itself, when I removed ('<SimpleCard/>')
from main function it worked fine.并且反应路由器初始页面本身是
('<SimpleCard/>')
,当我从主 function 中删除('<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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.