[英]React Functional Component props does not update
I use a functional component to display these divs.我使用一个功能组件来显示这些 div。 I have also another component that uses the displayCounter component and keeps track of a state.
我还有另一个组件,它使用 displayCounter 组件并跟踪状态。 My state is a counter and I have some buttons to increase and decrease the counter.
我的状态是一个计数器,我有一些按钮可以增加和减少计数器。
Let's say that the state is假设状态是
state = { counter: 0 }状态 = { 计数器:0 }
The div with the Example 1 does not display the changes of the counter. Example 1 的 div 不显示计数器的变化。 But the div with Example 2 works fine?
但是示例 2 的 div 工作正常吗?
So when I click to increase button div 1 always displays 0, but div 2 works fine.所以当我点击增加按钮 div 1 总是显示 0,但 div 2 工作正常。
Can somebody explain to me the reason?有人可以向我解释原因吗?
import React from 'react';
const displayCounter = (props) => {
return (
<div>
<div> Example 1: {props.value} </div>
<div> Example 2: <span>{props.value}</span> </div>
</div>
);
}
export default displayCounter;
Add a comment if you want to post the full code for the mini-app.如果您想发布迷你应用程序的完整代码,请添加评论。
import React, { Component } from 'react';
import CounterControl from '../../components/CounterControl/CounterControl';
import DisplayCounter from '../../components/DisplayCounter';
class Counter extends Component {
state = {
counter: 0
}
counterChangedHandler = () => {
this.setState( ( prevState ) => { return { counter: prevState.counter + 1 } } )
}
render () {
return (
<div>
<DisplayCounter value={this.state.counter}/>
<CounterControl label="Increment" clicked={() => this.counterChangedHandler( 'inc' )} />
</div>
);
}
}
export default Counter;
You should not use props, props is a old way, you should use this你不应该使用道具,道具是一种古老的方式,你应该使用这个
import React from 'react';
const displayCounter = ({ counter }) => {
return (
<div>
<div> Example 1: {counter} </div>
<div> Example 2: <span>{counter}</span> </div>
</div>
);
}
export default displayCounter;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.