react的一些总结(与vue的比较学习)

 最近有项目要用react搞了,之前只用过vue没接触过react咋办呀?  还能咋办,学起来了呀。 做了一点记录方便以后回顾。

1,组件通信

  (1)props通信:   这个很简单,和vue的差不多,父组件通过props传值给子组件,子组件可以通过props获取传递的内容。(建议加上类型检查,方便你我他)

//
import PropTypes from 'prop-types'
const { string } = PropTypes
function Test (props) {
  return (
    <div>
      {props.msg}
    </div>
  )
}
Test.propTypes = {
  msg: string
}
//
<Test msg="abc" />

  (2)Context:这个类似于vue的依赖注入

import React from 'react'
const TestContext = React.createContext()
const { Provider, Consumer } = TestContext
//
function Parent () {
  return (
    <div>
      <Provider value="abc">
        <Child/>
      </Provider>
    </div>
  )
}
//
function Child () {
  return (
    <Consumer>
      {(value) => (
          <div>
            {value}
          </div>
        )}
    </Consumer>
  )
}

  (3)路由传参: 和vueRouter的传参方式有些也基本类似

import React from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
function App () {
  return (
    <div>
      <Router>
        <ul>
          <li><Link to="/path/2">params方式</Link></li>
          <li><Link to={{pathname: '/query', query: { name: 'abc' }}}>query方式</Link></li>
          <li><Link to={{pathname: '/state', state: { name: 'def' }}}>state方式</Link></li>
        </ul>
        <Route path="/path/:id" component={List1}/>
        <Route path="/query" component={List2}/>
        <Route path="/state" component={List3} />
      </Router>
    </div>
  )
}
function List1 (props) {
// 刷新参数不丢失
  return(<div>{props.match.params.id}</div>)
}
function List2 (props) {
//刷新参数丢失
  return(<div>{props.location.query.name}</div>)
}
function List3 (props) {
// 刷新参数不丢失
  return(<div>{props.location.state.name}</div>)
}
以上都是BrowserRouter的结果,hash的没用过

  (4)redux: 这个得单独的学习,当然我们也可以使用useContext和useReducer实现一个简易的redux

import React, { createContext, useContext, useReducer } from 'react'
// 公共的context
const TestContext = createContext()

// 公共data
const initData = {
  msg: 'abc'
}
// 公共reducer
const reducer = (state, action) => {
  if (action.type === 'changeMsg') {
    return action.value
  } else  {
    return state
  }
}

// 通用的provider,作为根组织, 分发出state数据和dispatch修改函数
function Inject ({ children }) {
  const [state, dispatch] = useReducer(reducer, initData)
  return (
    <TestContext.Provider value={{state, dispatch}}>{children}</TestContext.Provider>
  )
}



export default function App () {
  return (
    <Inject>
      <Child/>
    </Inject>
  )
}

function Child () {
  const {state, dispatch} = useContext(TestContext)

  function handlerChange () {
    dispatch({
      type: 'changeMsg',
      value: {
        msg: 'def'
      }
    })
  }
  return (
    <div>
      <div>{state.msg}</div>
      <button onClick={handlerChange}>切换</button>
    </div>
  )
}

  (5)自定义事件: 这个是在网上看到的方法,使用node.js EventEmitter的浏览器版本来实现事件的监听和派发。

import React, { useState, useEffect } from 'react'
import { EventEmitter } from 'events'

const globalEvent = new EventEmitter()

export default function App () {
  return (
    <div>
      <Sibling1/>
      <Sibling2/>
    </div>
  )
}

function changeMsg () {
  globalEvent.emit('msgChange', 'def')
}

function Sibling1 () {
  return (
    <div>
      <button onClick={changeMsg}>切换msg</button>
    </div>
  )
}

function Sibling2 () {
  const [msg, changeMsg] = useState('abc')
  useEffect(() => {
    const eventEmitter = globalEvent.addListener('msgChange', newMsg => {
      changeMsg(newMsg)
    })
    return () => {
      globalEvent.removeListener(eventEmitter)
    }
  }, [])

  return (
    <div>{msg}</div>
  )
}

 

posted @ 2021-04-26 17:15  ken丶123  阅读(153)  评论(0编辑  收藏  举报