淘先锋技术网

首页 1 2 3 4 5 6 7

Updating with the useEffect dependency array

import React, { useState, useEffect } from "react"; // import {useState}
import ReactDOM from "react-dom";
import "./index.css";

function App() {
  const [val, setVal] = useState("");
  const [val2, setVal2] = useState("");
  
  // userEffect will be called after these renders useEffect 将在这些渲染后被调用
  useEffect(() => {
    console.log(`field 1:${val}`);
  }, [val]); // 第2个参数是依赖项数组,只有第1个input值变化时才执行前面一个参数即回调函数

  useEffect(() => {
    console.log(`field 2: ${val2}`);
  }, [val, val2]); // 2个input里有1个值变化就会打出log
  	//so we won't trigger unnecessary re-renders if we pass the right values to that array.
	//所以如果我们将正确的值传递给该数组,我们就不会触发不必要的重新渲染。

  return (
    <>
      <label>
        Favorite Phrase:
        <input value={val} onChange={(e) => setVal(e.target.value)} />
      </label>
      <br />

      <label>
        Second Favorite Phrase:
        <input value={val2} onChange={(e) => setVal2(e.target.value)} />
      </label>
    </>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

work in conjunction 协同工作
stateful hooks 有状态的钩子
userEffect will be called after these renders useEffect 将在这些渲染后被调用

so we won’t trigger unnecessary re-renders if we pass the right values to that array.
所以如果我们将正确的值传递给该数组,我们就不会触发不必要的重新渲染。

Fetching data with useEffect

// fetch data from github api, and then diplay it
function GitHubUser({ login }) {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(`https://api.github.com/users/${login}`)
    // 当然它只是一个 HTTP 响应,而不是真的 JSON。
    // 为了获取JSON的内容,我们需要使用 json() 方法
    //(该方法返回一个将响应 body 解析成 JSON 的 promise)
      .then((resp) => resp.json()) 
      .then(setData)
      .catch(console.error);
  }, []);

  if (data) {
    //return data;//error, user below JSON.stringify
    //return <div>{JSON.stringify(data)}</div>; //a little blob of stringified JSON data.
    return (
      <div>
        <h1>{data.login}</h1>
        <img src={data.avatar_url} width={100} alt="avatar" />
      </div>
    );
  }
  return null;
}

function App() {
  return <GitHubUser login="moonhighway" />;
}

ReactDOM.render(<App />, document.getElementById("root"));

fetch
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

concatenate onto the end of that string
连接到该字符串的末尾

So then we’re going to chain on our then function and we’re going to take the response from that API and we’re going to turn it into JSON.
然后我们将链接我们的 then 函数,我们将从该 API 获取响应,然后将其转换为 JSON。

a little blob of stringified JSON data. 一小块字符串化的 JSON 数据。

Using useReducer

function Checkbox() {
  const [checked, setChecked] = useState(false);

  return (
    <>
      <input
        type="checkbox"
        value={checked}
        onChange={() => {
          setChecked((checked) => !checked);
        }}
      />
      {checked ? "checked" : "unchecked"}
    </>
  );
}

ReactDOM.render(<Checkbox />, document.getElementById("root"));

=> extract 提炼出toggle:

function Checkbox() {
  const [checked, setChecked] = useState(false);

  function toggle() {
    setChecked((checked) => !checked);
  }
  return (
    <>
      <input type="checkbox" value={checked} onChange={toggle} />
      {checked ? "checked" : "unchecked"}
    </>
  );
}

=> 提炼到useReducer

import React, { useReducer } from "react"; 

function Checkbox() {
  const [checked, toggle] = useReducer((checked) => !checked, false);

  return (
    <>
      <input type="checkbox" value={checked} onChange={toggle} />
      {checked ? "checked" : "unchecked"}
    </>
  );
}

A reducer function’s most simple definition is that it takes in the current state, and it returns a new state.

Deploying a React app

Netlify

npm run build
npm install -g serve
serve -g build

找到项目的build目录,拖拽进netlify
完成:
https://amazing-wescoff-eb9876.netlify.app/