React Functional Component props does not update

这一生的挚爱 提交于 2021-02-10 16:55:35

问题


I use a functional component to display these divs. I have also another component that uses the displayCounter component and keeps track of a state. 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 }

The div with the Example 1 does not display the changes of the counter. But the div with Example 2 works fine?

So when I click to increase button div 1 always displays 0, but div 2 works fine.

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;

回答1:


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;


来源:https://stackoverflow.com/questions/64849867/react-functional-component-props-does-not-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!