当前位置 博文首页 > 文章内容

    react萌新的小复习

    作者: 栏目:未分类 时间:2020-08-04 16:02:39

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    入门小案例

    温馨提醒

    别跟vue/angular类型记得带上'/one',我总是弄错了

    <BrowserRouter>
                    <Link to={'/one'}>one</Link> <br/>
                    <Link to={'/two'}>two</Link> <br/>
                    <Link to={'/three'}>three</Link><br/>
                    <Switch>
                        <Route path={'/one'} component={One}/>
                        <Route path={'/two'} component={Two}/>
                        <Route path={'/three'} component={Three}/>
                    </Switch>
    </BrowserRouter>
    

    动态import

    美曰: 动态加载

    // math.js
    export function add(a, b) {
      return a + b;
    }
    
    import("./math").then(math => {
      console.log(math.add(16, 26));
    });
    

    懒加载组件

    之前
    import OtherComponent from './OtherComponent';
    之后
    const OtherComponent=React.lazy(()=>import('./OtherComponent'))
    

    setState

    this.setState({
        name:'xxx'
    })
    this.setState((state, props) => {
         /* 第一個參數函式 */
      return {新的state};
    },()=>{
         /* 第二個參數函式,state改變後執行 */
    });
    

    资料参考

    路由器

    BrowserRouter  常规URL路径
    HashRouter  哈希路由
    
    <Route path="/" exact>xxx</Route>  
    // exact  精准匹配
    <Switch> // 提供渲染路由
        <Router path={'/home'}>home</Router>
    </Switch>    
    

    导航

    <Link to="/home">Home</Link>
    // <a href="/">Home</a>
    <NavLink to="/react" activeClassName="aaa"> React </NavLink>
        // 给定默认的状态,给定的类是aaa
        exact 完全匹配
        strict 严格匹配,会考虑尾部斜杠
             <Route strict path={'/two/'}  component={Two}/>
    	isActive 
    	验证点击是否是活跃的状态
         <NavLink to={'three'} isActive={(match,location)=>{
                        console.log(match,location);
                        return false  // 返回Boolean 已经判断
                    }}>
    
    

    重定向

         <Route path={'/abc'}>
                                <Redirect to={'/ccc'}/>
        </Route>
    // '/abc' 重定向到 '/ccc'
     	 <Redirect to={{
                     pathname:'/three',
                     search:'?aaa=bbb',
                            }}/>
    push 重定向会重新推入历史记录,而不是替换当前
    <Redirect push to="/somewhere/else" />
    
    <Redirect from={'/three'} to={'/four'}/>
      从 /three => /four
    	exact 完全匹配
        strict 严格匹配
    
    =====
     <Link to={'/two/12'}>two</Link> <br/>
         
     <Route strict path={'/two'}  component={Two}/>
    
    function Two(props) {
        console.log(props.match);
        return (<div>
            two
        </div>)
    }  
    

    路由直接展示

      <Route path={'/two'} component={Two}></Route>
    
    <Route path={'/five'} render={() => <div>five</div>}/>
    可以执行参数处理
     <Route path={'/five'} render={(routeProps) => {
                            console.log(routeProps);
                            return <div>five</div>
                        }}/>
    

    render (鉴权)

    <Route path='/user' exact render={(props) => {
        // isLogin 从 redux 中拿到, 判断用户是否登录
        return isLogin ? <User {...props} name={'cedric'} /> : <div>请先登录</div>
    }}></Route>
    

    ReactHook(16.8)

    useState

    可以在一个组件多次使用

    function CounterOne() {
        const [count, setCount] = useState(10)
        const [a,setA]=useState(10)
        const increment = () => setCount(state => state + 1);
        return (<div>
            <h1>{count}</h1>
            <button onClick={increment}>点击</button>
        </div>)
    }
    

    useReducer

    function CounterOne() {
        const [count, increment] = useReducer(state => state + 1, 10)
        return (<div>
            < h1>{count}</h1>
            <button onClick={increment}>点击</button>
        </div>)
    }
    

    useEffect

    componentDidMount componentDidUpdate componentWillUnmount 具有相同的用途,只不过被合并成一个api

    更新dom节点
    function CounterOne() {
        const [count, increment] = useReducer(state => state + 1, 10)
        // 这个
        useEffect(()=>{
            document.title='更新了'
        })
        return (<div>
            < h1>{count}</h1>
            <button onClick={increment}>点击</button>
        </div>)
    }
    

    useHistory

    路由导航
    import { useHistory } from 'react-router-dom';
    
    function Home() {
      const history = useHistory();
      return <button onClick={() => history.push('/profile')}>Profile</button>;
    }
    

    useLocation

    类型于window.location ,它表示路由器的状态和位置

    import { useLocation } from 'react-router-dom';
    function CounterOne() {
        const location = useLocation();
        useEffect(() => {
            // 地址
            console.log(location.pathname);
            // 哈希
            console.log(location.search);
        })
        return (<div>
            <button onClick={increment}>点击</button>
        </div>)
    }
    

    拿到传递参数

    <Link to={{
                            pathname:'/seven/10',
                            state:{names:'ssss'}
                        }}>seven</Link>
    
    	const location = useLocation();
        useEffect(() => {
            console.log(location);//拿到了传递的参数
        })
    // 打印的参数
    hash: ""
    pathname: "/seven/10"
    search: ""
    state: {names: "ssss"}
    

    useParams

    提供URI搜索参数的访问

    动态ID查询

    /home/:id
    拿到这个id
    let {id} = useParams()
    

    useRouteMatch

    提供match对象的访问

    • params(key/value)
    • isExact(boolean) 路由是否被匹配
    • path(string) 匹配的路径模式
    • url(string) Link 跳过来的路径
    跳转到 /sevent/10
    本来是动态id匹配规则是 /sevent/:id
    const match = useRouteMatch();
        useEffect(() => {
            console.log(match);
        })
    打印的是一个object,其中的参数
    isExact: true
    params: {id: "10"}
    path: "/seven/:id"
    url: "/seven/10"
    

    Link

    函数的形式

    应用点: 当函数进行跳转的时候拿到之前的信息

     <Link to={location => {
                        console.log(location);
                        return ({...location, pathname: '/three'})
    }}>three</Link>