Answer the question
In order to leave comments, you need to log in
Why is the data from the 'options' state not output?
import React, { Component } from 'react';
import axios from 'axios';
export default class App extends Component {
state = {
searchValue: '',
options: [],
roots: [],
}
componentDidMount () {
axios.get(`https://swapi.co/api/`)
.then(data => {
var arr = [];
for (var key in data.data) {
arr.push(data.data[key]);
}
this.setState({ roots: arr });
})
.catch(err => console.log('Error: ', err));
}
onSearchChange = event => {
this.setState({ searchValue: event.target.value });
if (event.target.value.length >= 3) {
let newData = [];
this.state.roots.map((root) => {
axios.get(`${root}?search=${this.state.searchValue}`)
.then(data => {
data.data.results.map((item) => {
const rootName = root.split('/');
const searchItem = {
name: item.name,
rootName: rootName[4],
}
newData.push(searchItem)
});
})
.catch(err => console.log('Error: ', err));
})
this.setState({ options: newData });
console.log(this.state.options);
}
}
render() {
return (
<div>
<input value={this.state.searchValue} onChange={this.onSearchChange} />
{ this.state.options ?
<div className="options__list">
{ this.state.options.map( (item, index) => {
return (
<div
key={ index }
className="options__item"
>
<span className="options__text">
{item.name} - {item.rootName}
</span>
</div>
);
} ) }
</div> : null
}
</div>
)
}
}
Answer the question
In order to leave comments, you need to log in
The difference is when the code is executed.
The first two lines are executed immediately when the document is loaded. The variable num
is assigned the value of an empty input at that time.
The event listenerbtn
is hung on. It is not executed immediately, but sits and waits for the event. Each time an event occurs, the internal code of the function is executed.
The code inside the function - this one - is executed later when the button is pressed. Displays the value defined at the very beginning in a square. Or it takes a fresh, "for now" value from input'a in the second version of the code with "if instead of num, substitute document.get ...". getSquareNum()
alert()
num
Because num is a copy of the element's value.
It's better to make num be a pointer to the element itself:
var num = document.getElementById("number"); //здесь value опускаем
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
alert(num.value*num.value); //получаем текущее значение
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question