简体   繁体   English

ReactJS:解析错误:意外的令牌

[英]ReactJS : Parsing error: Unexpected token

class PostIndex extends Component {

    //define state
    const [posts, setPosts] = useState([]);

    //useEffect hook
    useEffect(() => {

        //panggil method "fetchData"
        fectData();

    }, []);

    //function "fetchData"
    const fectData = async () => {
        //fetching
        const response = await axios.get('http://localhost:3000/api/posts');
        //get response data
        const data = await response.data.data;

        //assign response data to state "posts"
        setPosts(data);
    
    }
}


export default PostIndex;

please help me, i new learning at react js.请帮助我,我在 React js 中新学习。 i was about make class name PostIndex, so i change from function PostIndex() to class PostIndex extends Component.我打算将类名命名为 PostIndex,所以我从函数 PostIndex() 更改为类 PostIndex 扩展组件。 and get error from this line const [posts, setPosts] = useState([]);并从此行获取错误 const [posts, setPosts] = useState([]); could you help me?你可以帮帮我吗? please.请。 thanks谢谢

You cant use react class components with react hooks.你不能使用带有反应钩子的反应类组件。

So the right solution will be something like this:所以正确的解决方案是这样的:

const PostIndex = () => {

  //define state
  const [posts, setPosts] = useState([]);

  //useEffect hook
  useEffect(() => {

      //panggil method "fetchData"
      fectData();

  }, []);

  //function "fetchData"
  const fectData = async () => {
      //fetching
      const response = await axios.get('http://localhost:3000/api/posts');
      //get response data
      const data = await response.data.data;

      //assign response data to state "posts"
      setPosts(data);
  }

  return your markup
}

You can't use hooks in the class components, check docs rather use functional component:您不能在类组件中使用钩子, 请查看文档而不是使用功能组件:

const PostIndex = () => {
  const [posts, setPosts] = useState([]);
  // rest of your code....
  }

  export default PostIndex;

You can't use React Hooks such as useState in class component.你不能在类组件中使用诸如 useState 之类的 React Hooks。 It only works in functional component.它仅适用于功能组件。 If you want to use state in class component, please follow as:如果你想在类组件中使用状态,请遵循:

class PostIndex extends React.Component {
   state = {posts: []}; // define state
        .....
   this.setState({
       posts: ['a', 'b']
   }); // set state
        .....
   let temp = this.state.posts; // use state
        .....

I hope this will help you.我希望这能帮到您。 Thanks.谢谢。

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

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