React 新官网遇上 Cursor 智能编辑器

629 阅读1分钟

前言

近期 React 发布了新官网
新款编辑器 cursor 带着 GPT-4 来了,安装即可使用,这是下载地址
两者相遇会发生什么好玩的事情呢?

Using Hooks

在 React 官网中 Using Hooks 章节有下面一段话,但是没有相关示例,那就去找个示例看看。

Q: Hooks are more restrictive than other functions. You can only call Hooks at the top of your components (or other Hooks). If you want to use useState in a condition or a loop, extract a new component and put it there.

A: It is true that Hooks are more restrictive than other functions. You can only call Hooks at the top of your components (or other Hooks). If you want to use useState in a condition or a loop, extract a new component and put it there. This is because Hooks rely on the order in which they are called, and calling them conditionally or in a loop can lead to unexpected behavior.

For example, if you have the following code in "./src/components/ExampleComponent.js":

import React, { useState } from "react"

function ExampleComponent() {
  const [count, setCount] = useState(0)

  if (count === 0) {
    const [name, setName] = useState("John")
  }

  return (
    <div>
      <p>{name}</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  )
}

export default ExampleComponent

You will get an error that "name" is not defined when you click the button. This is because the useState hook for "name" is called conditionally, and React cannot guarantee that it will be called every time the component renders.

To fix this, you can extract a new component and put the conditional logic there. For example:

import React, { useState } from "react"

function ExampleComponent() {
  const [count, setCount] = useState(0)

  return (
    <div>
      {count === 0 ? <NameComponent /> : null}
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  )
}

function NameComponent() {
  const [name, setName] = useState("John")

  return <p>{name}</p>
}

export default ExampleComponent

Now, the useState hook for "name" is only called when the "NameComponent" is rendered, and React can guarantee that it will be called every time the component renders.

感触

React 新纯英文官网阅读下来感觉很舒服,结合智能编辑器不会嫌弃英语不好和要回答些奇奇怪怪的问题,增强代码能力的同时提升英文水平,智能编辑器真的是好强啊,大家快去玩呀,have fun ~