Reactjs 带有React功能部件的偶数计数器
我试图通过只使用函数组件而不是类方法来重新编写下面的“偶数计数器”示例 这是原稿: 代码Reactjs 带有React功能部件的偶数计数器,reactjs,react-hooks,Reactjs,React Hooks,我试图通过只使用函数组件而不是类方法来重新编写下面的“偶数计数器”示例 这是原稿: 代码 类ShouldComponentUpdate扩展了React.Component{ 建造师(道具){ 超级(道具) 此.state={ 数值:0 } this.addValue=this.addValue.bind(this) } 附加值(){ this.setState((状态)=>({ 值:state.value+1 })) } 渲染(){ 返回( 添加 ) } } 仅类evens扩展React.Com
类ShouldComponentUpdate扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
数值:0
}
this.addValue=this.addValue.bind(this)
}
附加值(){
this.setState((状态)=>({
值:state.value+1
}))
}
渲染(){
返回(
添加
)
}
}
仅类evens扩展React.Component{
建造师(道具){
超级(道具)
}
shouldComponentUpdate(下一步,下一步状态){
如果(nextrops.value%2==0)返回true
}
渲染(){
返回(
{this.props.value}
)
}
}
好吧,我试着做下面的事情,但我在回调函数中失败了。有人能复习一下吗
代码
函数组件应更新(){
常量[计数器,设置计数器]=使用状态(0)
返回(
设置计数器(计数器+1)}>添加
)
}
const EvenCounter=React.memo({counter})=>{
函数检查偶数(nextrops,nextState){
如果(nextrops.counter%2==0){
//迷失在这里
}
}
返回(
{计数器}
)
})
您应该将计数器逻辑分离到您自己的自定义挂钩中,例如useEvenCounter
。因为钩子是可组合的,所以它可以在其他任何地方重用,而不仅仅是在特定的组件中
函数UseEventCounter(初始值:number=0){
const[value,setValue]=React.useState(initialValue);
常量增量=React.useCallback(
()=>设置值((v)=>(v%2===0?v+2:v+1)),
[]
);
返回[value,increment]作为常量;
}
用法
导出默认函数App(){
常量[值,增量]=UseEventCounter();
const[value2,increment2]=useEventCounter(1);
返回(
你好,代码沙盒
开始编辑,看看神奇的发生!
增量()}>+
{value}
递增2()}>+
{value2}
);
}
现场演示
你可以在下面的现场演示中玩。如果你什么都不懂就给我打电话
谢谢,但主要问题是我不想在奇数上重新渲染。该函数应仅以偶数更新render。我不知道如何替换函数组件上的shouldComponentUpdate(),而不是使用类。
class ShouldComponentUpdate extends React.Component {
constructor (props) {
super(props)
this.state = {
value: 0
}
this.addValue = this.addValue.bind(this)
}
addValue () {
this.setState((state) => ({
value: state.value + 1
}))
}
render () {
return (
<div>
<button onClick={this.addValue}>Add</button>
<OnlyEvens value={this.state.value} />
</div>
)
}
}
class OnlyEvens extends React.Component {
constructor (props) {
super(props)
}
shouldComponentUpdate (nextProps, nextState) {
if (nextProps.value % 2 === 0) return true
}
render () {
return (
<div>
<h1>{this.props.value}</h1>
</div>
)
}
}
function ComponentShouldUpdate () {
const [counter, setCounter] = useState(0)
return (
<div>
<button onClick={() => setCounter(counter + 1)}>Add</button>
<EvenCounter counter={counter} />
</div>
)
}
const EvenCounter = React.memo(({ counter }) => {
function checkEven (nextProps, nextState) {
if (nextProps.counter % 2 === 0) {
//lost in here
}
}
return (
<div>
<h2>{counter}</h2>
</div>
)
})