首页 > 解决方案 > 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 };

标签: javascriptreactjs

解决方案


上面的组件('<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

推荐阅读