react学习手册

0.warning

  1. 不要修改props
  2. 不要直接修改this.state(而是应该使用 setState())
  3. state的更新是异步的,所以state的状态更新时不要同时相互依赖,但是可以通过传入函数延迟更新,这样就解决了
    同时也可以将后续操作变成回调函数放在第二个参数上保证执行顺序
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));
  1. 不需要watch,因为每次state变化都会触发render,直接把操作写在render中就行
  2. 没有class,用className
  3. dom对象要么不换行好么用()包裹
  4. dom元素只包含一个根dom元素,或者用带key的map
  5. 参数过多时,直接用{…obj}进行传递,组件的props都是能接受到的
  6. 设置props默认值只要
  7. 所有函数必须用bind硬绑定,要么就匿名函数
  8. 插入html文本
<p dangerouslySetInnerHTML={{__html:"<div>nmad</div>"}}></p>
component.defaultProps = {
}
或者内部
static defaultProps = {
	  name: 'stranger'
}
  1. props类型检查
Toolbar.propTypes = {
	changeTheme: PropTypes.func
};

11.template
空标签或者<React.Fragment>

1.生命周期

其中mount和update之前都会执行render

  1. 挂载卸载过程
    1.1.constructor()
    1.2.componentWillMount()(过时了)
    static getDerivedStateFromProps()代替,现在只比较props前后变化
    1.3.componentDidMount()
    1.4.componentWillUnmount ()
  2. 更新过程
    2.1.componentWillReceiveProps (nextProps)(过时了)
    static getDerivedStateFromProps()代替,现在只比较props前后变化
    2.2.shouldComponentUpdate(nextProps,nextState)
    2.3.componentWillUpdate (nextProps,nextState)(过时了)
    getSnapshotBeforeUpdate(prevProps, prevState)代替,此时的值与didMount中一致
    2.4.componentDidUpdate(prevProps,prevState)
    2.5.render()

2.条件渲染

  1. 在render中判断,然后把给对象赋不同值
  2. 在子组件中判断,不同返回值
if (isLoggedIn) {
	button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
	button = <LoginButton onClick={this.handleLoginClick} />;
}

return (
	<div>
		<Greeting isLoggedIn={isLoggedIn} />
		{button}
	</div>
);

3.v-if(等价)

使用&&或者三目运算符或者内部返回false
注意,内部返回false组件生命周期仍然

{
	  unreadMessages.length > 0 &&
	  <h2>
		You have {unreadMessages.length} unread messages.
	  </h2>
}
{
	this.state.showWarning ?
	<WarningBanner warn={this.state.showWarning} />:
	'' 
}
function WarningBanner(props) {
	if (!props.warn) {
		return null;
	}

	return (
		<div className="warning">
			Warning!
		</div>
	);
}

4.使用provider

  1. 创建
const ThemeContext = React.createContext('light');
// 设置react-devtools中context的名字
ThemeContext.displayName = 'MyDisplayName';
  1. 使用
这个是非必须的,但是组件会使用优先近的provider,没有就使用默认值
<ThemeContext.Provider value="dark">
	  <Toolbar />
</ThemeContext.Provider>
  1. 获取
3.1 直接注册获取
static contextType = ThemeContext;
或者
ThemedButton.contextType = ThemeContext
这样都可以在this拿到context
render() {
	  return <Button theme={this.context} />;
}

3.2 不注册获取
<ThemeContext.Consumer>
	{value => value}
</ThemeContext.Consumer>
或使用hook获取
function Example() {
  const locale = useContext(LocaleContext);
  const theme = useContext(ThemeContext);
  // ...
}

5.使用组件注册

//已弃用的方法
与vue一样,dom上用ref注册,然后用this.refs.xx来引用
//第二种方法,在state上添加
<section ref="(dom) => this.state.dom = dom">
//现在的方法,在构造函数中先声明注册名,然后在模板中注册
//注意ref正常情况下传给function组件无效
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}
const node = this.myRef.current;
//注意myRef可以传递而不直接使用,因此也可以操作孙子节点行为,这是第三种方法优越之处
// 第四种方法,使用ref回调函数,传入的时候自动会把当前dom作为第一个参数进行执行
class CustomTextInput extends React.Component {
	constructor(props) {
		super(props);

		this.textInput = null;

		this.setTextInputRef = element => {
			console.log(element)
			this.textInput = element;
		};

		this.focusTextInput = () => {
			// 使用原生 DOM API 使 text 输入框获得焦点
			if (this.textInput) this.textInput.focus();
		};
	}

	componentDidMount() {
		// 组件挂载后,让文本框自动获得焦点
		this.focusTextInput();
	}

	render() {
		// 使用 `ref` 的回调函数将 text 输入框 DOM 节点的引用存储到 React
		// 实例上(比如 this.textInput)
		return (
			<div>
				<input
					type="text"
					ref={this.setTextInputRef}
				/>
				<input
					type="button"
					value="Focus the text input"
					onClick={this.focusTextInput}
				/>
			</div>
		);
	}
}

6.组件转发

//这是函数组件专用写法
//这是把自身的ref转发到了子组件button上
//注意可以设置函数名或者其displayName修改tools中显示的名字
const MyFunctionComponent = React.forwardRef((props, ref) => {
	  return <LogProps {...props} ref={ref} />;
});

//当然也可以中间组件不要用ref接受组件引用,用props进行传递
//我觉得直接用props更直观更好,不要搞什么花里胡哨的组件转发
// 最常见的HOC传递方法,先用React.forwardRef转发,然后转发的时候ref变成props,然后装饰组件将props转给子组件
function logProps(Component) {
  class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);
    }

    render() {
      const {forwardedRef, ...rest} = this.props;

      // 将自定义的 prop 属性 “forwardedRef” 定义为 ref
      return <Component ref={forwardedRef} {...rest} />;
    }
  }

  // 注意 React.forwardRef 回调的第二个参数 “ref”。
  // 我们可以将其作为常规 prop 属性传递给 LogProps,例如 “forwardedRef”
  // 然后它就可以被挂载到被 LogProps 包裹的子组件上。
  return React.forwardRef((props, ref) => {
    return <LogProps {...props} forwardedRef={ref} />;
  });
}

7.vscode插件快捷键

  1. rcc 生成组件模板
  2. rccp 生成带props验证的模板

8.同级传值

使用pubsub

// 发起者
Pubsub.publish("evt",this.state.name)
//接受者
Pubsub.subscribe("evt",(msg, data) => {
    console.log(msg);//evt
    console.log(data);//this.state.name即son11
})

9.模拟数据

json-server

json-server 文件名.json --port 4000

10.路由匹配

如下,第二个路由无论当前hash是啥都能匹配到

<Route path="/home" component={Son}></Route>
<Route path="/" component={Son}></Route>

为了解决这个问题,添加属性exact解决

<Route path="/home" component={Son}></Route>
<Route path="/" component={Son} exact></Route>

如果一组路由中只想匹配一个外部可以加<Switch>
如果有重定向的需求:

<Redirect from="/" to="/home" exact></Redirect>

关于二级路由吧二级组件写在一级组件中,注意二级路由的url要写全
如果要监控路由变化

history.listen((link) => {
	//link是当前的新location
})

如果要手动跳转路由

props.history.push('/home')

如果要路由传参

//params方法
// 1.先设置参数
<Route path="/home/:id" component={Son}></Route>
// 2.发送参数
<Link to="/home/99">点我起飞</Link>
// 3.接收参数
console.log(props.match.props.params.id)
// 但是上述方法的缺点在于只能传字符串
//query方法
// 1.发送参数
<Link to={ pathname: "/home", query: { name: 'zl' } }>点我起飞</Link>
// 2.接收参数
console.log(props.location.query.name)

11.高阶组件(HOC)

就是将组件作为参数,返回也是一个组件

比如
export default withRouter(home);
将location、match、history添加到props上,即使该组件不是一个route

12.hook

给函数组件使用状态特性用的
useState()返回一个数组
arr[0]是那个状态,arr[1]是修改状态的函数(类似setState)
如果定义多个状态

let arr = userState({
	val1: 0,
	val2: 1,
	val3: 2,
})
// 使用状态
console.log(arr[0].val1)
// 修改状态(没错,这里只能全体修改)
arr[1]({
	val1: 2,
	val2: 3,
	val3: 4,
})
// 当然也可以多次声明,将不同状态独立
// 这样的话注意useState和副作用的顺序

hook的生命周期也被简化,useEffect表示componentDidMount、componentDidUpdate 和 componentWillUnmoun

function Example() {
  const [count, setCount] = useState(0);

  // 相当于 componentDidMount 和 componentDidUpdate:
  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // 这里的返回值函数会在componentWillUnmoun触发
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  return (
    <div>
      ...
    </div>
  );
}

关于自定义hook,感觉上是用来提取重复的判断逻辑

13.优化

用scu只在某些数据更新时才重新渲染,减少不必要的渲染

class CounterButton extends React.Component {
  constructor(props) {
    ...
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

  render() {
    return (
      ...
    );
  }
}
或者使用浅比较,当然浅比较如果发现属性变化前后的引用一样,那么他不会触发渲染
class CounterButton extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {count: 1};
  }

  render() {
    return (
      <button
        color={this.props.color}
        onClick={() => this.setState(state => ({count: state.count + 1}))}>
        Count: {this.state.count}
      </button>
    );
  }
}

14.portal

这是一种将元素渲染到任意dom的方法,但是注意react树的关系没有变化
因此点击事件等仍然可以按react树的形式冒泡

render() {
  // React 并*没有*创建一个新的 div。它只是把子元素渲染到 `domNode` 中。
  // `domNode` 是一个可以在任何位置的有效 DOM 节点。
  return ReactDOM.createPortal(
    this.props.children,
    domNode
  );
}

15.redux(react版本的状态管理工具)

//设置监听,触发页面修改
componentDidMount() {
	store.subscribe(() => {
		this.setState({
			num: store.getState()
		})
	})
}

react-redux不再使用subscribe,而是用provider组件中注入store,
connect( mapStateToProps, mapDispatchToProps)(component)来封装store的输入输出规则
在7.1版本后也可以用useSelector和useDispatch来使用代替connect

16.useMemo和useEffect有什么区别

他们都是副作用(类似hook或者生命周期这样),但是useMemo和useEffect的执行时机不同。useEffect会在dom更新完之后执行,而useMemo会在dom渲染时就执行,所以不要在useMemo中书写触发渲染的操作.
应用场景:
1.useMemo+memo可以实现父组件重渲染,子组件不重新渲染
2.useMemo化的函数如果在模版中立即执行,那么useMemo未监听的变量变化时该函数也不会再执行一次。

useCallback(fn, deps) 相当于 useMemo(() => fn, deps)

17.renderProps

render prop 是一个用于告知组件需要渲染什么内容的函数 prop

18.redux-thunk的作用

直接作用:dispatch中可以接受一个以dispatch本身作为第一个参数的函数了
间接作用:现在异步操作可以放在action里了(因为action是个函数),更加解耦合

19.redux-saga的作用

可以和redux-thunk互相替代

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智慧校园整体解决方案是响应国家教育信息化政策,结合教育改革和技术创新的产物。该方案以物联网、大数据、人工智能和移动互联技术为基础,旨在打造一个安全、高效、互动且环保的教育环境。方案强调从数字化校园向智慧校园的转变,通过自动数据采集、智能分析和按需服务,实现校园业务的智能化管理。 方案的总体设计原则包括应用至上、分层设计和互联互通,确保系统能够满足不同用户角色的需求,并实现数据和资源的整合与共享。框架设计涵盖了校园安全、管理、教学、环境等多个方面,构建了一个全面的校园应用生态系统。这包括智慧安全系统、校园身份识别、智能排课及选课系统、智慧学习系统、精品录播教室方案等,以支持个性化学习和教学评估。 建设内容突出了智慧安全和智慧管理的重要性。智慧安全管理通过分布式录播系统和紧急预案一键启动功能,增强校园安全预警和事件响应能力。智慧管理系统则利用物联网技术,实现人员和设备的智能管理,提高校园运营效率。 智慧教学部分,方案提供了智慧学习系统和精品录播教室方案,支持专业级学习硬件和智能化网络管理,促进个性化学习和教学资源的高效利用。同时,教学质量评估中心和资源应用平台的建设,旨在提升教学评估的科学性和教育资源的共享性。 智慧环境建设则侧重于基于物联网的设备管理,通过智慧教室管理系统实现教室环境的智能控制和能效管理,打造绿色、节能的校园环境。电子班牌和校园信息发布系统的建设,将作为智慧校园的核心和入口,提供教务、一卡通、图书馆等系统的集成信息。 总体而言,智慧校园整体解决方案通过集成先进技术,不仅提升了校园的信息化水平,而且优化了教学和管理流程,为学生、教师和家长提供了更加便捷、个性化的教育体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值