React的onClick事件在每次渲染时触发,传统解决方法不起作用。

huangapple go评论71阅读模式
英文:

React onClick event fires every render, traditional solutions not working

问题

我有一个基本的React程序,它使用Axios来获取有关电影的数据,然后将其打印给用户。Axios请求,以及因此打印信息,不应该发生,直到用户点击底部的按钮。

import "./styles.css";
import axios from "axios";
import { useState } from "react";

export default function App() {
  const [movie, setMovie] = useState("");
  const [title, setTitle] = useState("");
  const [runTime, setRunTime] = useState("");

  function getMovie(e) {
    setMovie(e.target.value);
  }

  console.log(movie);

  function axiosRequest() {
    return axios.get(
      "https://www.omdbapi.com/?t=" + movie + "&y=&plot=short&apikey=trilogy"
    );
  }

  const handleButtonClick = () => {
    axiosRequest().then(function (results) {
      var response = results.request.response;
      var responseObj = JSON.parse(response);

      console.log(responseObj);
      setTitle(responseObj.Title);
      setRunTime(responseObj.Runtime);
    });
  };

  return (
    <div>
      <h1 style={{ textAlign: "center" }}>
        [在此处插入电影搜索引擎的名称]
      </h1>
      <p>Hello请问您想了解哪部电影</p>
      <input type="text" onChange={getMovie} />
      <br />
      <br />
      <button onClick={handleButtonClick}>提交</button>
      <br />
      <br />
      Title: {title}
      <br />
      Runtime: {runTime}
    </div>
  );
}

在这里,我将axiosRequest函数的调用放在了一个新的handleButtonClick函数内,并将该函数绑定到按钮的onClick事件上。这样,Axios请求只会在用户点击按钮后触发,而不会在每次渲染时都触发。

英文:

I have a primitive React program that uses Axios to get data about movies and then print it for the user. The Axios request, and thus printing of information, isn't supposed to happen until after the user clicks the button at the bottom.

    import &quot;./styles.css&quot;;
import axios from &quot;axios&quot;;
import { useState } from &quot;react&quot;;
export default function App() {
const [movie, setMovie] = useState(&quot;&quot;);
const [title, setTitle] = useState(&quot;&quot;);
const [runTime, setRunTime] = useState(&quot;&quot;);
function getMovie(e) {
setMovie(e.target.value);
}
console.log(movie);
function axiosRequest() {
return axios.get(
&quot;https://www.omdbapi.com/?t=&quot; + movie + &quot;&amp;y=&amp;plot=short&amp;apikey=trilogy&quot;
);
}
axiosRequest().then(function (results) {
var response = results.request.response;
var responseObj = JSON.parse(response);
console.log(responseObj);
setTitle(responseObj.Title);
setRunTime(responseObj.Runtime);
});
return (
&lt;div&gt;
&lt;h1 style={{ &quot;text-align&quot;: &quot;center&quot; }}&gt;
[INSERT CATCH NAME FOR MOVIE SEARCH ENGINGE HERE]
&lt;/h1&gt;
&lt;p&gt;Hello, what movie would you like to know about:&lt;/p&gt;
&lt;input type=&quot;text&quot; onChange={getMovie} /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;button onClick={axiosRequest}&gt;submit&lt;/button&gt;
&lt;br /&gt;
&lt;br /&gt;
Title: {title}
&lt;br /&gt;
Runtime: {runTime}
&lt;/div&gt;
);
}

I've tried writing the event handler as {axiosRequest} and {() =&gt; axiosRequest} and {() =&gt; axiosRequest()} and even {() =&gt; axiosRequest(params)} but nothing works. There's still the same problem. I even tried attaching .then to the definition of the axiosRequest function, but React didn't like that. Nor did it like me removing the parentheses and writing it as axiosRequest.then which I thought might stop the function from firing on every render.

So what's the deal? How do I fix this? I don't want it to start printing movie data until after the user hits the button.

答案1

得分: 1

将执行数据获取和处理的代码移入一个单独的函数中。目前这些代码直接在组件内部,并且会在每次渲染时执行。

function fetchData() {
  axiosRequest().then(function (results) {
    // ...
    setTitle(responseObj.Title);
    setRunTime(responseObj.Runtime);
  });
}

function handleClick() {
  fetchData();
}
<button onClick={handleClick}>提交</button>
英文:

Move the code that performs fetching and handling the data into a separate function. Currently that code is directly inside the component and will be executed on each render.

function handleClick() {
	axiosRequest().then(function (results) {
		// ...
		setTitle(responseObj.Title);
		setRunTime(responseObj.Runtime);
	});
}
&lt;button onClick={handleClick}&gt;submit&lt;/button&gt;

huangapple
  • 本文由 发表于 2023年7月11日 05:18:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定