简体   繁体   中英

How to get a react component to rerender without forceupdate?

I'm trying to learn react by building a simple web app where a user can upload an image and apply different effects to them. I hit a bit of a road block. I'm trying to figure out how to rerender the imagecontainer after the user clicks one of the effects. I read about forceupdate but it's not recommended to use. Here my code:

import React, { Component } from 'react';

import ImageContainer from './components/image_container';
import AppliedContainer from './components/applied_container';
import UnappliedContainer from './components/unapplied_container';

class App extends Component {

constructor(props) {
    super( props );
    this.state = {
        transform :  false  ,
        rotate : false  ,
        scale : false   ,
        opacity : false 
    }

};


render() {
    return (
        <div className="row">
            <ImageContainer onChange={this.state} />
            <UnappliedContainer types={this.state} onSelect={ state => 
     this.setState(state) }/>
            <AppliedContainer types={this.state} onSelect={ state => 
     this.setState(state) }/>             
        </div>
    );
}

}

export default App;

Thanks Guys!

It depends on what onChange is doing inside of ImageContainer. If you want to rerender ImageContainer then onChange inside of ImageContainer could call this.setState to set the state of ImageContainer to its new props.

You could also use the componentWillRecieveProps, or componentShouldUpdate lifecycle methods to trigger a rerender.

http://busypeoples.github.io/post/react-component-lifecycle/

According to React's nature, updating the component without using forceUpdate is changing your state

<ImageContainer onChange={this.state} />

I don't really understand what you pass here as props (onChange), shouldn't it be a function, instead of your state-object?

In my opinion, you should create some function in the App component, in that function, you change your state by this.setState({...}) , then you pass this function into your child component as props. Besides, please also remember to bind that function into the App component

Since you are new to React, would you mind writing other components' code as well, and tell me what you want for the behaviors of all components, so we can find the best way together

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