Answer the question
In order to leave comments, you need to log in
New dynamically created component not rendering?
I'm learning react. The bottom line is this, If you write the Component with all the parameters in the state with handles, it is rendered. If I send an Ajax request to the server, I receive a response with a new object, and I add it to the state, this same Component is no longer rendered. It means that it is rendered by handles, and when it comes from the server it is not rendered. As I understand it, the problem is that the render does not work to draw new components?
import React, {Component} from 'react';
import Circle from './Circle';
let xhr;
class NewApp extends Component{
constructor(props){
super(props);
this.state={
arrays:[<Circle key='99' bgColor='red' />]
}
this.sob = this.sob.bind(this);
this.req = this.req.bind(this);
}
// Запрос
sob(){
xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:3001", true);
xhr.send();
xhr.addEventListener("readystatechange",this.req, false);
}
// Обработка запроса установка состояния с новыми данными
req(){
if(xhr.readyState === 4 && xhr.status === 200){
var response = JSON.parse(xhr.responseText);
this.state.arrays.push(<Circle key={this.state.arrays.length} bgColor={response.color} />)
}
}
render(){
return[
<div>
<div key="9324"><button key={77} onClick={this.sob}>Ещё инфа</button></div>
{this.state.arrays}
</div>
]
}
}
export default NewApp;
import React from "react";
import ReactDOM from "react-dom";
import NewApp from './NewApp';
ReactDOM.render(
<NewApp />,
document.getElementById("root")
);
Answer the question
In order to leave comments, you need to log in
Solution found. It consisted of setting setState, without pushing.
req(){
if(xhr.readyState === 4 && xhr.status === 200){
var response = JSON.parse(xhr.responseText);
console.log('2. Пришел ответ от сервера:', response)
console.log('Текущее состояние state{arrays :',this.state.arrays)
console.log('Какой ключ будет у компонента в Циркле ', this.state.arrays.length)
this.setState((state,props)=>{
return {arrays: [state.arrays ,<Circle key={1} bgColor={response.color} />]};
})
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question