简体   繁体   中英

expected assignment or function call: no-unused-expressions ReactJS functional component

this is my first react app and I don't understand what's wrong.I'm trying to display the page but I'm getting the error in the title twice(on lines 26:5 - where the fetch(url, { is and 39:9 where I have the line setisLoaded(true), setArticles(result.articles);) .I changed the code back and forth from App class component to functional component,but no luck(though fetching the data works/worked).I tried enclosing all the code inside the useEffect() method into a return statement only to have all sort of parsing errors that I can't fix.So here's the code:

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;

Initially I wanted to be able to change the country parameter from the URL in order to fetch the desired content from the API,based on what's submitted from the form(I know I should have a select with options instead of an input type text,but I'm just testing this for now).But at this point,I'm just happy if I'll be able to display any page,since the other responses to this issue(adding a return to the useEffect() arrow function,enclosing statements within parenthesis instead of curly braces) didn't work for me and I don't understand this error.Any idea would be appreciated.

One error is for these:

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

Statements are separated by semicolons, not commas, so the fix is:

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

One error is a misplaced parentheses, which is causing the error callback to be a separate expression:

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

It should instead be:

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

You are missing the dependencies array in the useEffect.

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

If you add an empty array it will only fetch the data once when your component mounts. If you add any prop or state inside the array it will fetch when the component mounts and also when the prop or state added changes.

Always remember to add the array as a second parameter of the useEffect to avoid that infinite loop.

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