标签: react-lifecycle

在 shouldComponentUpdate 中 nextState 做了什么?

在 React 生命周期函数shouldComponentUpdate(nextProps, nextState) 中, nextProps 是不言自明的。

但是 nextState 做什么呢?

在决定是否应该渲染/修改组件之前,我可以评估即将到来的状态,这听起来不太对。

reactjs react-lifecycle

5
推荐指数
2
解决办法
5496
查看次数

使用 React Hooks,为什么我的事件处理程序以不正确的状态触发?

我正在尝试div使用 React 钩子创建此旋转示例的副本。https://codesandbox.io/s/XDjY28XoV

到目前为止,这是我的代码

import React, { useState, useEffect, useCallback } from 'react';

const App = () => {
  const [box, setBox] = useState(null);

  const [isActive, setIsActive] = useState(false);
  const [angle, setAngle] = useState(0);
  const [startAngle, setStartAngle] = useState(0);
  const [currentAngle, setCurrentAngle] = useState(0);
  const [boxCenterPoint, setBoxCenterPoint] = useState({});

  const setBoxCallback = useCallback(node => {
    if (node !== null) {
      setBox(node)
    }
  }, [])

  // to avoid unwanted behaviour, deselect all text
  const deselectAll = () => …
Run Code Online (Sandbox Code Playgroud)

event-listener reactjs react-lifecycle react-hooks react-lifecycle-hooks

5
推荐指数
1
解决办法
3202
查看次数

在react中snapshot和prevState、prevProps来自componentDidUpdate有什么不同?

我刚刚开始学习React。

在学习 LifeCycle 时,我想知道componentDidUpdate方法。

据我所知,componentDidUpdate方法可以有三个参数(prevProps, prevState, snapshot)。prevState如果我能从中找出componentDidUpdatesnapshot为了什么?

这可能不重要,但我只是很好奇

reactjs react-lifecycle

5
推荐指数
1
解决办法
2176
查看次数

如何使用重组库中的 HoC 创建 React 的新静态函数 getDerivedStateFromProps 作为生命周期方法?

最近有消息称 React 很快就会被弃用componentWillReceiveProps,取而代之的是新的静态函数getDerivedStateFromProps在这里查看更多内容

getDerivedStateFromProps我目前正在将我的应用程序迁移到这个新的 API,但由于我正在将重构库用于更高阶的组件,所以我遇到了问题。componentWillReceive我们通过库的生命周期对象来使用props。

所以在转向新的 API 之前,我有以下内容:

export function someHoC () {
  return compose(
    lifecycle({
      componentWillReceiveProps (nextProps) {
        const { fetch } = nextProps
          if (shouldFetch(this.props, nextProps)) {
             fetch()
          }
      }
    })
  )
}
Run Code Online (Sandbox Code Playgroud)

现在已更改为以下内容:

export function someHoC () {
  return compose(
    lifecycle({
      getDerivedStateFromProps (nextProps) {
          const { fetch } = nextProps
          if (shouldFetch(this.props, nextProps)) {
             fetch()
          }
      }
    })
  )
}
Run Code Online (Sandbox Code Playgroud)

但是,getDerivedStateFromProps需要是静态的,所以我收到了有关此问题的警告,并且不知道如何处理它。

warning.js?7f205b4:33 警告:lifecycle(MyComponent):getDerivedStateFromProps() 被定义为实例方法,将被忽略。相反,将其声明为静态方法。

我该怎么做才能将它作为静态生命周期方法传递到我的组件中?

reactjs recompose higher-order-components react-lifecycle

3
推荐指数
1
解决办法
8313
查看次数

在 react.js 的 componentDidMount() 中执行提取之前,如何通过 navigator.geolocation 获取用户的位置?

我已经尝试了各种不同的方法,但我被难住了。在 React 中使用 promise 和进行 api 调用的新手。这就是我目前所拥有的:

import React, { Component } from 'react'
import Column from './Column'
import { CardGroup } from 'reactstrap';

let api = "https://fcc-weather-api.glitch.me/api/current?";


class App extends Component {

    constructor(props) {
        super(props)
        this.state = {
            isLoaded: false,
            items: {},
        }

    this.fetchWeather = this.fetchWeather.bind(this)
}

fetchWeather(apiStr) {
    fetch(apiStr)
        .then(res => res.json())
        .then(

            (result) => {

                console.log(result)
                this.setState({
                    isLoaded: true,
                    items: result.main
                });
                console.log(this.state);
            },
            // Note: it's important to handle errors here
            // instead of a catch() …
Run Code Online (Sandbox Code Playgroud)

geolocation fetch reactjs es6-promise react-lifecycle

3
推荐指数
1
解决办法
6769
查看次数

React:render() 之后和子构造函数之前的函数调用

我有一个名为Parent的组件,其中有另一个名为Child 的组件:

<Parent>
  <Child/>
</Parent>
Run Code Online (Sandbox Code Playgroud)

所以生命周期如下:

  1. 父构造函数
  2. 父母的渲染()
  3. 子构造函数
  4. 孩子的渲染()
  5. 孩子已安装
  6. 父级已挂载

我可以在第 2 步之后和第 3 步之前以某种方式进行额外的父初始化吗?

更新:

<Parent>
  <Child/>
</Parent>
Run Code Online (Sandbox Code Playgroud)
class ThirdPartyLib {
  init(elementId) {
    console.log(`initializing element: ${elementId}`);
    // element with #id: elementId should exist!
    // document.getElementById(elementId).style.color = "red";
  }
}

class Parent extends React.Component {
    constructor(props) {
        super(props);
        console.log("Parent's constructor");
    }

    render() {
        console.log("rendering Parent");
        new ThirdPartyLib().init("parent");
        return (
            <div id="parent">Parent: {this.props.name}
                <Child name="Sara"/>
            </div>
        );
    }

    componentDidMount() {
        console.log("Parent is mounted");
    }
} …
Run Code Online (Sandbox Code Playgroud)

reactjs react-lifecycle react-component

3
推荐指数
1
解决办法
4684
查看次数

React 函数组件 useEffect 钩子,其依赖关系在类组件生命周期中相等

我在带有依赖项的功能组件内使用 useEffect 钩子,以便依赖项发生变化,useEffect 函数将像这样重新运行:

const [show, setShow] = React.useState(false);

React.useEffect(() => {
 
    console.log("Do something")

} , [show]);
Run Code Online (Sandbox Code Playgroud)

我想知道 React 的类组件中有什么可以做到这一点?有没有任何生命周期方法可以实现此功能?

javascript reactjs react-lifecycle react-hooks react-lifecycle-hooks

3
推荐指数
1
解决办法
4264
查看次数

当我有“display: none”时,将调用 ComponentDidMount 函数

我正在根据属性有条件地渲染模态组件display

show我需要在组件/上实现切换主体滚动功能hide

参见下面的实现,

演示组件

<button onClick={()=> this.setState({ show: true })}>Show modal</button>
<Modal show={show} containerStyle={containerStyle} position={position} handleClickOutside={()=> this.setState({ show: false })} >
  <Content />
</Modal>
Run Code Online (Sandbox Code Playgroud)

模态组件

componentDidMount() {
  disableBodyScroll(this.state.defaultMargin);
}

componentWillUnmount() {
  enableBodyScroll(this.state.defaultMargin);
}

render() {
  const { show } = this.props;
  const display = show ? 'block' : 'none';
  return (
    <div onClick={ handleClickOutside } className={ styles[ 'modal'] } style={ { display } }>
      {children}
    </div>
  );
}

Run Code Online (Sandbox Code Playgroud)

但问题是在显示模态之前调用了 componentDidMount 函数。我希望在模态显示后调用它

当 Modal 隐藏时,应该调用 componentWillUnmount …

reactjs react-lifecycle

2
推荐指数
1
解决办法
1742
查看次数

在 ReactJS 中调用挂载函数

当组件加载到 ReactJS 上时,我在调用函数时遇到问题。我尝试使用 componentDidMount() 并编译错误。请检查我下面的代码。谢谢

export default function Customers() {
    const classes = useStyles();
    const searchBarStyles = useStyles2();
    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(10);
    const dispatch = useDispatch();

    const handleChangePage = (event, newPage) => {
      setPage(newPage);
    };

    const handleChangeRowsPerPage = (event) => {
      setRowsPerPage(+event.target.value);
      setPage(0);
    };

    const fetch = () => {
      dispatch(fetchPendingAdmissions());
    };

    componentDidMount() {
        fetch()
    }

    return (
      <div>
        <h1 className={classes.h1}>Customers</h1>
        <Paper component="form" className={searchBarStyles.root}>
          <InputBase
            className={searchBarStyles.input}
            placeholder="Search..."
            inputProps={{ 'aria-label': 'search...' }}
          />
          <IconButton type="submit" …
Run Code Online (Sandbox Code Playgroud)

reactjs react-redux react-lifecycle react-lifecycle-hooks

2
推荐指数
1
解决办法
1万
查看次数

在 componentDidUpdare 中 React setState 导致超出最大更新深度

我正进入(状态

错误:超出最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。React 限制嵌套更新的数量以防止无限循环。

但我读到的内容应该能够在 componentDidMount 中调用 setState 而不会出现错误。

class MyComponent extends Component {
constructor(props) {
    super(props);
    this.state = {
        matchtedProducts: [],
        products: [],
    }
}
async componentDidMount() {
    try {
        const products = await getProducts()
        this.setState({ products })
    } catch(err) {
        console.log(err)
    }
}

componentDidUpdate() {
    const productColor = this.props.size.trim().toLowerCase()
    const productSize = this.props.color.trim().toLowerCase()
    const matches = []

    this.state.products.map(product => {
        const title = product.title
        const titleSpliitet = title.split(',')

        let color = titleSpliitet[1].trim().toLowerCase()
        let …
Run Code Online (Sandbox Code Playgroud)

javascript setstate reactjs react-lifecycle

2
推荐指数
1
解决办法
1万
查看次数