1. 程式人生 > 實用技巧 >react萌新的小複習

react萌新的小複習

入門小案例

溫馨提醒

別跟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>