简体   繁体   English

为什么我在 React 中的 function 被调用了两次但执行不均?

[英]Why is my function in React being called twice but not equaly executed?

This is my function in my home.js React App, with all the needed logs:这是我的 home.js React 应用程序中的 function,包含所有需要的日志:

function pin(){
  console.log('function pin()');
  var result = []
  var url = "http://warm-hamlet-63390.herokuapp.com/pin/list"
  axios.get(url)
  .then((res)=>{
    console.log('after .then');
    if(res.data){
      console.log('inside pin() if');
      for(var i in res.data.data)
      {
          result.push([i, res.data.data[i]])
      }
    }
    console.log('after pin() if');
  })
  console.log('end of pin()');
  return result;
}

Immediately after the function, I have my exported function that renders the page:在 function 之后,我立即导出了呈现页面的 function:

export default function App(){
  const{isLoaded, loadError} = useLoadScript({
    googleMapsApiKey: "my_api_key",
    libraries,
  })

  const [markers, setMarkers] = React.useState([]);
  if(loadError) return "Erro a carregar o mapa"
  if(!isLoaded) return "Carregando"

  return <div>
    {pin()}
    <GoogleMap 
    mapContainerStyle={mapContainerStyle} 
    zoom={11} 
    center={center}
    >
    <Marker
      position={
        {
           lat: 2, 
           lng:2
        }
      }
      icon={nivelpin.verde}
    >
    </Marker>

    </GoogleMap>
    
  </div>
}

The JSON file that the URL is being set to has 7 records in it, but as you can see in the image, it's being executd twice. URL 设置为的 JSON 文件中有 7 条记录,但正如您在图像中看到的那样,它被执行了两次。

The function is only executing twice inside the .then((res)=>{ function 仅在 .then .then((res)=>{

Why is that?这是为什么? Is it something to do with axios?和 axios 有关系吗?

Image: https://media.discordapp.net/attachments/656598463638798357/852982191029747732/unknown.png图片: https://media.discordapp.net/attachments/656598463638798357/852982191029747732/unknown.png

EDIT: Added the logs and the function App() + Image that shows the logs:编辑:添加了日志和 function App() + 显示日志的图像:

https://media.discordapp.net/attachments/656598463638798357/852995551691276368/unknown.png https://media.discordapp.net/attachments/656598463638798357/852995551691276368/unknown.png

You're calling a function in the template that is returned.您在返回的模板中调用 function。 Meaning that function is going to get called on every render.这意味着 function 将在每次渲染时被调用。

You have to store the results to a variable which gets rendered in your component.您必须将结果存储到在您的组件中呈现的变量中。 Something like this:像这样的东西:

class App extends Component {
  constructor() {
    super();
    this.state = { data: [] };
  }

  componentDidMount() {
    fetch(`https://api.coinmarketcap.com/v1/ticker/?limit=10`)
      .then(res => res.json())
      .then(json => this.setState({ data: json }));
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.data.map(el => (
            <li>
              {el.name}: {el.price_usd}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

( source ) 来源

OR if you want to stick with a functional component:或者,如果您想坚持使用功能组件:

function App() {
  const [data, setData] = useState({ hits: [] });
 
  useEffect(async () => {
    const result = await axios(
      'https://hn.algolia.com/api/v1/search?query=redux',
    );
 
    setData(result.data);
  });
 
  return (
    <ul>
      {data.hits.map(item => (
        <li key={item.objectID}>
          <a href={item.url}>{item.title}</a>
        </li>
      ))}
    </ul>
  );
}
 
export default App;

( source ) 来源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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