Skip to content

[2020-03-06]React專案問題紀錄 #43

Description

@pdji1602003

前言

利用這篇issue記錄一下我最近在React上碰到的問題。

問題

react-issue

  1. 以上console會報錯的原因出於我在處理事件監聽時沒有使用回呼函數。什麼意思呢?看一下以下的程式碼。

正確寫法:

<button onClick={() => handleClick("hello")}>Click</button>

錯誤寫法:
此寫法會導致此按鈕在未被點擊情況下立即調用此handleClick
這是相當低級的錯誤,請注意勿再犯

<button onClick={handleClick("hello")}>Click</button>
  1. React更新列表的思路流程,詳見以下程式碼:
    //目前已知什麼樣的資訊,基於那樣的資訊去達到我們想要的目的
    //已有資訊id, recipe
    //目的是更新recipe
    //更新特定recipe的步驟是,複製既有的recipes,找到待更新的recipe,將新增加的recipe與既有的recipe進行抽換
function handleRecipeChange(id, recipe){
    const newRecipes = [...recipes]
    const index = newRecipes.findIndex(r => r.id === id)
    newRecipes[index] = recipe
    setRecipes(newRecipes)
  }
  1. 有無使用spread operator的差異:
const recipe ={
	name:'name', 
	amount:'amount', 
	number:1
}
const change = {
	number:2
}
const result = {...recipe, change}
console.log('結果', result)

result

4. 理解`useEffect`的調用時機:`useEffect`會在組件渲染完成後調用。
const endpoint = "https://api.github.com/users/codeartistryio";

// with promises:
function App() {
  const [user, setUser] = useState(null)
  
  useEffect(() => {
    console.log('組件生成渲染完成後即調用useEffect')
    fetch(endpoint)
      .then(response => response.json())
      .then(data => setUser(data))//在此調用到setUser更改state狀態,組件會再重新繪製一次
  }, [])

  return (
    <div>
      {console.log('我會在第一輪渲染印出,以及每次state更新時印出')}
      {/* 第二次渲染,fetch已完成,所以會在畫面上顯現user.id */}
      {user && user.id}
    </div>
  )
}
  1. 如何寫出一個custom hook:注意一下useAPI裡程式碼的執行順序
//寫一個抓取API並返回抓取結果的custom hook
function useAPI(URL){
  const [value, setValue] = useState([])
  
  useEffect(()=>{
    console.log('第二印出')
    getData()
    console.log('第三印出')
  },[])

  async function getData(){
    const response = await fetch(URL)
    const data = await response.json()
    console.log('第四印出')
    setValue(data)
  }

  console.log('最先印出&&最後印出')
  return (value)
}

function App(){
  const todos = useAPI('https://todos-dsequjaojf.now.sh/todos')
  
  return(
    <ul>
      {todos && todos.map(todo => <li key={todo.id}>{todo.text}</li>)}
    </ul>
  )
}

參考

以上內容部分參考此篇The React Cheatsheet for 2020 (+ real-world examples)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ReactEverything about React

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions