React挂钩无法在JSX中映射数组

时间:2020-04-16 02:50:44

标签: javascript reactjs react-hooks jsx

我确实在互联网的许多地方进行了搜索,但终生无法找到解决问题的方法。

我无法在React的JSX中通过数组进行映射。在过去,我已经能够轻松完成此操作,但是由于某些原因,当我决定练习一些React Hooks时,事情变得太棘手了。

这是我的代码:

import "./App.css";
import axios from "axios";

const Search = () => {

// takes information written in input field.
  const handleChange = (e) => {
    e.preventDefault();
    const lookUp = e.target.value;
    setSearchTerm(lookUp);
    return lookUp;
  };

  // useState for searcing the term in the search box
  const [searchTerm, setSearchTerm] = useState("");

  // useState for submitting the form and getting a result
    const [word, setWord] = useState("")
    const [definitions, setDefinitions] = useState("")


  const handleSubmit = (e) => {
    const apiKey = "secretsecret";
    const apiURL = `https://www.dictionaryapi.com/api/v3/references/thesaurus/json/${searchTerm}?key=${apiKey}`;
      e.preventDefault();

    axios({
      method: "GET",
      url: apiURL,
      dataResponse: "json",
    }).then((res) => {

        res.data.map(wordInfo => {

            const wordArray = Object.values(wordInfo)
            setWord(wordInfo.hwi.hw)

            if (wordInfo.hwi.hw === searchTerm) {

                const defsArray = wordInfo.shortdef;

                setDefinitions(defsArray)

                const syns = wordInfo.meta.syns;
                syns.map(synWords => {
                    synWords.map(wordsLol => {


                    })
                })
            }
        })
    });
  };

return (
  <div>
    <div className="searchForm">

      <form action="" onSubmit={handleSubmit}>
        <label htmlFor="searchBox">Look up a word</label>
        <input type="text" id="searchBox" onChange={handleChange} />
        <input type="submit" value="Search me!" />
      </form>
    </div>
        <div className="wordInfo">
            {definitions.map(test => {
                console.log(test)
            })}
        </div>
  </div>
);
};

export default Search;

别管那些la脚的变量名,这只是我的练习项目。

任何输入肯定会有所帮助。我似乎在做什么错了?

3 个答案:

答案 0 :(得分:0)

在此处初始化空数组:

const [definitions, setDefinitions] = useState([])

答案 1 :(得分:0)

除了将初始化definitions作为数组以防止像@Nilanka Manoj所描述的那样映射字符串外,在map之后呈现HTML语法时,请确保已放置return。例如:

<div className="wordInfo">
            {definitions.map(test => {
                return (
                   //your HTML syntax
                )
            })}
</div>

或者您可以这样做

<div className="wordInfo">
            {definitions.map(test => (
                   //your HTML syntax
            ))}
</div>

答案 2 :(得分:0)

您在searchTerm中使用handleSubmit来引用一个闭包值。 React不会在每次渲染时更新handleSubmit函数,因此您总是获得旧值searchTerm,当用户单击时该值为空。

您可以使用useCallback并将searchTerm添加为依赖项

const handleSubmit = useCallback((e) => {
    const apiKey = "secretsecret";
    const apiURL = `https://www.dictionaryapi.com/api/v3/references/thesaurus/json/${searchTerm}?key=${apiKey}`;
      e.preventDefault();

    axios({
      method: "GET",
      url: apiURL,
      dataResponse: "json",
    }).then((res) => {

        res.data.map(wordInfo => {

            const wordArray = Object.values(wordInfo)
            setWord(wordInfo.hwi.hw)

            if (wordInfo.hwi.hw === searchTerm) {

                const defsArray = wordInfo.shortdef;

                setDefinitions(defsArray)

                const syns = wordInfo.meta.syns;
                syns.map(synWords => {
                    synWords.map(wordsLol => {


                    })
                })
            }
        })
    });
  }, [searchTerm]);