简体   繁体   中英

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,

How can I prevent this behavior? I hope I may need to use 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 };

Above component ('<SimpleCard/>') was called by the parent component 2 times.

Accidently I listed ('<SimpleCard/>') in parent component. And react router initial page was ('<SimpleCard/>') itself, when I removed ('<SimpleCard/>') from main function it worked fine.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM