Reactjs React是否因道具而渲染组件?
根据该链接:Reactjs React是否因道具而渲染组件?,reactjs,Reactjs,根据该链接: render()可以通过新道具触发。有人能给我一个代码示例吗?我看不出道具是如何变化的!请不要通过国家改变道具;然后是setState()调用render()..看看-这是它的签名-它返回一个布尔值。这里有道具,您可以比较并手动确定组件是否应该更新 shouldComponentUpdate(nextProps, nextState) 对于功能组件React.memo是与类组件一起使用的shouldComponentUpdate的替代品 const myComponent=Rea
render()
可以通过新道具触发。有人能给我一个代码示例吗?我看不出道具是如何变化的!请不要通过国家改变道具;然后是setState()
调用render()
..看看-这是它的签名-它返回一个布尔值。这里有道具,您可以比较并手动确定组件是否应该更新
shouldComponentUpdate(nextProps, nextState)
对于功能组件React.memo
是与类组件一起使用的shouldComponentUpdate
的替代品
const myComponent=React.memo(props=>{
...
React.FunctionComponent的代码
...
},
(prevProps,nextProps)=>prevProps.propA===nextProps.propA
);
React.memo
获取上面显示的两个参数:React.FunctionComponent(将由memo
包装)和返回布尔值的可选函数
当函数返回true时,将不会重新呈现组件。如果省略该函数,则其在React.memo
中的默认实现与React.PureComponent中的shouldComponentUpdate
的实现类似。例如,它对道具
进行了肤浅的比较,区别在于只考虑了道具
,因为功能组件不存在状态
。使用挂钩更容易显示。传递给ComponentB的新道具数据会导致ComponentB重新呈现:
import React, { useState } from 'react'
import ComponentB from '...'
const ComponentA = props => {
const [data, setData] = useState(0) // data = 0
handleChangeProp = item => setData(item) // data = 1
return(
<div>
<button onClick{() => handleChangeProp(1)}
<ComponentB props={data} />
</div>
)
}
import React,{useState}来自“React”
从“…”导入组件B
常量组件a=props=>{
const[data,setData]=useState(0)//data=0
handleChangeProp=item=>setData(item)//数据=1
返回(
handleChangeProp(1)}
)
}
是的,当您执行设置状态(newState)或传入更改的道具时,组件将重新渲染,这就是为什么您不能进行变异。以下将不起作用,因为您将state设置为mutated state
export default function Parent() {
const [c, setC] = useState({ c: 0 });
console.log('in render:', c);
return (
<div>
<button
onClick={() =>
setC(state => {
state.c++;
console.log('state is:', state);
return state;
})
}
>
+
</button>
<Child c={c.c} />
</div>
);
}
要指示React中的更改,您必须创建一个新引用:
const a = {c:1};
const b = {...a};//b is shallow copy of a
a===b;//this is false, even though both a and b have same internal values
这意味着您还可以进行非预期的渲染,因为您创建的对象道具可能具有相同的值,但仍然是与上次创建时不同的参照
请注意,即使
const a = {c:1};
const b = {...a};//b is shallow copy of a
a===b;//this is false, even though both a and b have same internal values