在 React 生命周期函数shouldComponentUpdate(nextProps, nextState) 中, nextProps 是不言自明的。
但是 nextState 做什么呢?
在决定是否应该渲染/修改组件之前,我可以评估即将到来的状态,这听起来不太对。
我正在尝试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
我刚刚开始学习React。
在学习 LifeCycle 时,我想知道componentDidUpdate方法。
据我所知,componentDidUpdate方法可以有三个参数(prevProps, prevState, snapshot)。prevState如果我能从中找出componentDidUpdate是snapshot为了什么?
这可能不重要,但我只是很好奇
最近有消息称 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() 被定义为实例方法,将被忽略。相反,将其声明为静态方法。
我该怎么做才能将它作为静态生命周期方法传递到我的组件中?
我已经尝试了各种不同的方法,但我被难住了。在 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) 我有一个名为Parent的组件,其中有另一个名为Child 的组件:
<Parent>
<Child/>
</Parent>
Run Code Online (Sandbox Code Playgroud)
所以生命周期如下:
我可以在第 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)我在带有依赖项的功能组件内使用 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
我正在根据属性有条件地渲染模态组件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 上时,我在调用函数时遇到问题。我尝试使用 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) 我正进入(状态
错误:超出最大更新深度。当组件在 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) react-lifecycle ×10
reactjs ×10
javascript ×2
react-hooks ×2
es6-promise ×1
fetch ×1
geolocation ×1
react-redux ×1
recompose ×1
setstate ×1