React的一些小API(路由懒加载,setState的参数类型)

这篇博客探讨了React中的setState方法,强调了它可以接收对象或函数作为参数,并详细解释了当传递函数时如何处理state更新。此外,文章还介绍了React Router的懒加载概念,展示了如何使用Suspense组件来处理路由的懒加载,以及在出现错误时提供加载指示器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import React, { Component, setState, lazy, Suspense } from 'react'
import { Route, Link } from 'react-router-dom'

/**
 * setState可以传递一个对象也可以传递一个函数一个参数如果传递函数会上接受两个参数一个state,props
 * 函数的方式默认会返回更新以后的state数值
 * 路由的懒加载
 */
// export default class App extends Component {
//   state={count:0}
//   handle=()=>{
//     this.setState(state=>state.count+=10)
//   }
//   render() {

//     return (
//       <div>
// {this.state.count}
//         <button onClick={this.handle}>增加</button>
//       </div>
//     )
//   }
// }


/**
 * 直接出现的错误
 * Error: A React component suspended while rendering, but no fallback UI was specified.

Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.
解决办法
 * 定义懒路由
 */
const Home = lazy(() => import('./list/index'))
export default class App extends Component {
  render() {
    return (
      <div>
        <Link to='/list'>list</Link>
        <Suspense fallback={<h1>....</h1>}>        <Route path="/list" component={Home}>
        </Route></Suspense>

      </div>
    )
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值