简体   繁体   中英

React Functional Component props does not update

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM