Teoman shipahi
Teoman shipahi

Reputation: 23122

Typescript React componentDidMount not getting called

I am trying to run some sample with typescript/react, but for some reason componentDidMount function is not getting fired, and I would like to move my AJAX logic in there.

Here is my code below.

var app = new MyAppApplication();

namespace MyAppApp.Components {
    // props?: P, context?: any
    export class HomePageView extends React.Component<any, any> {
        constructor(props, context) {
            super(props, context);
            this.state = null;
            // calling here
            console.log("constructor");
        }
        public componentDidMount() {
        // not calling here
            console.log("componentDidMount");
        }
        public render() {
            var view = this.state.map((item, index) =>
                <div className="MyAppBoxContainer" key={index}>
                    <a href={item.Href}>{item.Title}</a>
                    </div>
            );
            return (<div>{view}</div>);
        }

    }
}


app.getHomeContentTitles().then(result => {
    //app.logger.info(this, result);
    var main = new MyAppApp.Components.HomePageView("1", result);
    main.state = result;
    var mainView = main.render();
    ReactDOM.render(mainView, document.getElementById(app.templateContainer));
}).catch(err => {
    app.logger.error(this, err);
});

Am I missing something?

Upvotes: 2

Views: 19385

Answers (1)

rossipedia
rossipedia

Reputation: 59427

Don't call your component's render() method yourself. Also, don't instantiate it yourself. Also, pass props in to your component, rather than setting state directly:

Change this:

var main = new MyAppApp.Components.HomePageView("1", result);
main.state = result;
var mainView = main.render();
ReactDOM.render(mainView, document.getElementById(app.templateContainer));

To this:

ReactDOM.render(
    <MyAppApp.Components.HomePageView result={result} />,
    document.getElementById(app.templateContainer)
);

If JSX is not supported, then you can do:

ReactDOM.render(
    React.createElement(MyAppApp.Components.HomePageView, { result: result}),
    document.getElementById(app.templateContainer)
);

Then access results via this.props.result rather than this.state:

public render() {
    return (
        <div>
            {this.props.result.map((item, index) =>
                <div className="MyAppBoxContainer" key={index}>
                    <a href={item.Href}>{item.Title}</a>
                </div>
            )}
        </div>
    );
}

Upvotes: 5

Related Questions