簡體   English   中英

React JS,整個 react 組件渲染兩次

[英]React JS, entire react component renders two times

下面的 API 調用從服務器獲取數據 2 次,導致我的反應組件向 DOM 呈現 2 次,

如何防止這種行為? 我希望我可能需要使用 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

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/>') ,當我從主 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM