react的一些总结(与vue的比较学习)
最近有项目要用react搞了,之前只用过vue没接触过react咋办呀? 还能咋办,学起来了呀。 做了一点记录方便以后回顾。
1,组件通信
(1)props通信: 这个很简单,和vue的差不多,父组件通过props传值给子组件,子组件可以通过props获取传递的内容。(建议加上类型检查,方便你我他)
// 子 import PropTypes from 'prop-types' const { string } = PropTypes function Test (props) { return ({props.msg}) } Test.propTypes = { msg: string } // 父
(2)Context:这个类似于vue的依赖注入
import React from 'react' const TestContext = React.createContext() const { Provider, Consumer } = TestContext //父 function Parent () { return () } //子 function Child () { return ({(value) => ( ) }{value})}
(3)路由传参: 和vueRouter的传参方式有些也基本类似
import React from 'react' import { BrowserRouter as Router, Route, Link } from 'react-router-dom' function App () { return () } function List1 (props) { // 刷新参数不丢失 return(
- params方式
- query方式
- state方式
{props.match.params.id}) } function List2 (props) { //刷新参数丢失 return({props.location.query.name}) } function List3 (props) { // 刷新参数不丢失 return({props.location.state.name}) } 以上都是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 (
{children}
)
}
export default function App () {
return (
)
}
function Child () {
const {state, dispatch} = useContext(TestContext)
function handlerChange () {
dispatch({
type: 'changeMsg',
value: {
msg: 'def'
}
})
}
return (
{state.msg}
)
}
(5)自定义事件: 这个是在网上看到的方法,使用node.js EventEmitter的浏览器版本来实现事件的监听和派发。
import React, { useState, useEffect } from 'react'
import { EventEmitter } from 'events'
const globalEvent = new EventEmitter()
export default function App () {
return (
)
}
function changeMsg () {
globalEvent.emit('msgChange', 'def')
}
function Sibling1 () {
return (
)
}
function Sibling2 () {
const [msg, changeMsg] = useState('abc')
useEffect(() => {
const eventEmitter = globalEvent.addListener('msgChange', newMsg => {
changeMsg(newMsg)
})
return () => {
globalEvent.removeListener(eventEmitter)
}
}, [])
return (
{msg}
)
}