【问题标题】:expected assignment or function call: no-unused-expressions ReactJS functional component预期的赋值或函数调用:no-unused-expressions ReactJS 功能组件
【发布时间】:2020-12-19 17:00:03
【问题描述】:

这是我的第一个反应应用程序,我不明白出了什么问题。我正在尝试显示页面,但标题中出现两次错误(在第 26:5 行 - fetch(url, { 是和 39:9 我有 setisLoaded(true), setArticles(result.articles);) 行。我将代码从 App 类组件来回更改为功能组件,但没有运气(尽管获取数据有效/有效)。我尝试将所有代码包含在 useEffect 中() 方法变成一个返回语句,只是为了有各种我无法修复的解析错误。所以这里是代码:

import React, { Fragment, useState, useEffect } from 'react';
    import Title from './components/Title/Title';
    import Content from './components/Content/Content';
    import 'bootstrap/dist/css/bootstrap.min.css';
    import { Card, Navbar, Form, FormControl, Button } from 'react-bootstrap';
    
    const App = (props) => {
      const [error, setError] = useState(null);
      const [isLoaded, setisLoaded] = useState(false);
      const [articles, setArticles] = useState([]);
      const [country, setCountry] = useState('gb');
    
      const handleSubmit = (event) => {
        event.preventDefault();
        changeCountryHandler();
      };
    
      const changeCountryHandler = (event) => {
        setCountry(event.target.value);
      };
    
      useEffect(() => {
        let url =
          'https://cors-anywhere.herokuapp.com/http://newsapi.org/v2/top-headlines?country='
+
          country;
        fetch(url, {
          method: 'GET',
          headers: {
            Accept: 'application/json, text/plain, */*',
            'Content-type': 'application/json',
            'x-api-key': 'myApiKey',
            SameSite: 'None',
          
          },
        })
          .then((res) => res.json())
    
          .then((result) => {
            setisLoaded(true), setArticles(result.articles);
          }),
          (error) => {
            setisLoaded(true);
            setError(error);
          };
      });
    
      if (error) {
        return <div>Error: {error.message}</div>;
      } else if (!isLoaded) {
        return <div>Loading...</div>;
      } else {
        return (
          <>
            <Navbar className="bg-secondary justify-content-between" variant="dark">
              <p>The selected country is:{country}</p>
              <Form inline onSubmit={handleSubmit}>
                <FormControl
                  type="text"
                  placeholder="Search by country"
                  className=" mr-sm-2"
                  onChange={changeCountryHandler}
                  value={country}
                />
                <Button type="submit">Submit</Button>
              </Form>
            </Navbar>
            {articles.map((article) => (
              <Card
                style={{ width: '100%', height: 'auto' }}
                key={article.title}
                className="mb-5 mt-4 bg-light"
              >
                <Card.Img
                  variant="top"
                  src={article.urlToImage}
                  className="pr-3 pl-3"
                  alt=""
                />
    
                <Card.Body>
                  <Card.Title>
                    {article.author} | {article.publishedAt}
                    <Title title={article.title}>{article.title}</Title>
                  </Card.Title>
                  Description: {article.description}
                  <Content content={article.content}>{article.content}</Content>
                  Read the full article on{' '}
                  <Card.Link
                    href={article.url}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    {article.url}
                  </Card.Link>
                </Card.Body>
              </Card>
            ))}
          </>
        );
      }
    };
    
    export default App;

最初,我希望能够根据从表单提交的内容更改 URL 中的国家/地区参数,以便从 API 中获取所需的内容(我知道我应该有一个带有选项而不是输入类型的选择文本,但我现在只是对此进行测试)。但是在这一点上,如果我能够显示任何页面,我会很高兴,因为对此问题的其他响应(添加返回到 useEffect()箭头函数,用括号而不是花括号括起来的语句)对我不起作用,我不明白这个错误。任何想法将不胜感激。

【问题讨论】:

    标签: javascript reactjs use-effect


    【解决方案1】:

    其中一个错误是:

    setisLoaded(true), setArticles(result.articles);
    

    语句用分号而不是逗号分隔,因此修复方法是:

    setisLoaded(true);
    setArticles(result.articles);
    

    一个错误是括号放错了位置,这导致错误回调是一个单独的表达式:

    }), // <-----
    (error) => {
      setisLoaded(true);
      setError(error);
    };
    

    应该是:

    }, (error) => {
      setisLoaded(true);
      setError(error);
    }); // <----- moved to here
    

    【讨论】:

    • 谢谢你的回答。这解决了一个问题,但现在我有另一个问题。现在我有错误:位置 0 错误的 JSON 中的意外令牌 T。许多请求一直在该服务器上发送,我有在 30 秒内发送了数百个请求,我正在淹没服务器。这可能是什么原因?
    • 您的组件设置为在每次呈现时发送请求。如果您只想在组件挂载时发送它,则需要在 useEffect 的末尾添加一个空的依赖数组。 useEffect(() =&gt; { /*your existing effect code here */ }, [])
    【解决方案2】:

    您在 useEffect 中缺少依赖项数组。

    useEffect(() => {
       //your code
    }, []);
    

    如果您添加一个空数组,它只会在您的组件挂载时获取一次数据。如果您在数组中添加任何道具或状态,它将在组件挂载以及添加的道具或状态更改时获取。

    始终记得将数组作为 useEffect 的第二个参数添加以避免无限循环。

    【讨论】:

    • 谢谢 Nicholas 和 andoni。这解决了我的问题。
    猜你喜欢
    • 2019-03-31
    • 2020-04-21
    • 2020-11-20
    • 2020-07-31
    • 1970-01-01
    • 2021-11-17
    • 2021-08-23
    • 2019-08-15
    • 2020-12-10
    相关资源
    最近更新 更多