React-useContext & useReducer的使用

实战

使用 React.js 创建一个具有 2 个页面的应用,要求:

  1. 有两个页面:首页和二级页
  2. 首页中有一个数字(n),二级页里也有一个数字(n),还有两个按钮:-1 和 +1。按 -1 则数字自减 1,+1 则自增 1
  3. 改变一级页面的数字,进入二级页面数字也同样改变;使用 useContext & useReducer
  4. 二级页内需要有按钮或链接来返回首页
点击查看代码
import React, { createContext, useContext, useReducer } from "react";
import { Link, Route, Routes, useLocation } from "react-router-dom"
import "./App.css";

const CountContext = createContext(0);

function App() {
    return (
        <div className="App">
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/secondary" element={<Secondary />} />
            </Routes>
        </div>
    )
}

const Home = () => {
    const [count, dispatch] = useReducer((state, action) => {
        switch (action) {
            case 'add':
                return state + 1;
            case 'sub':
                return state - 1;
            default:
                return state;
        }
    }, useContext(CountContext));
    return (
        <div className="div">
            <h2>
                <strong style={{ textAlign: "center" }}>{count}</strong>
            </h2>
            <button onClick={() => { dispatch('add') }}>+1</button>
            <button onClick={() => { dispatch('sub') }}>-1</button>
            <h3>
                <Link to={"/secondary"} state={{ value: count }}>Secondary</Link>
            </h3>
        </div>
    )
}

function Secondary() {
    const count = useLocation()
    return (
        <div className="div">
            <h1>
                <strong style={{ textAlign: 'center' }}>{count.state.value}</strong>
            </h1>
            <h3>
                <Link to="/">返回</Link>
            </h3>
        </div>
    )
}




export default App;
posted @ 2022-08-18 19:50  lanercifang  阅读(42)  评论(0)    收藏  举报