Я работаю над некоторым кодом. В основном, когда нажимается кнопка 1 (id = 1), отображается ее значение (где id === 1). При нажатии кнопки 2 отображается значение кнопки «2» и т. д. Код работает нормально.
constructor(props) {
super(props);
this.state = {
collections: [],
collection: [],
initialVal: [],
};
choseSeason = event => {
// console.info(event.target.id);
this.setState({
initialVal: event.target.id,
}, () => console.info('initialVal: '+this.state.initialVal));
}
componentDidMount() {
axios.get(`https://myapi`)
.then(res => {
const collections = res.data;
this.setState({
collections,
collection: collections.map(collection=>(collection)),
//this is console log line 29
initialVal: collections[0].id,
});
})
}
render() {
const { collections = [] } = this.state;
const collection = this.state;
const nowId = collections.filter(collection => collection.id === this.state.initialVal);
console.info(nowId); //this is console log line 56
return (
<Container className = "collection">
<div className = "">
{collections.length ? collections.map(c=>(
<div className = "nav"><NavLink activeClassName = {"active3"} onClick = {this.choseSeason}><span id = {c.id}>{'SS'+c.name.slice(7, 9)}</span></NavLink></div>
))
:
<React.Fragment/>
}
</div>
{nowId.length ?
<div className = "wrapper">
<div className = "item1 flex">
<div className = "flex right">
<div className = "title vBot">
{nowId[0].collection_titles[0].title}
</div>
</div>
...
Поток:
ComponentDidMount получает значение из первых данных из моего API и переводит его в состояние (InitialVal)
в Render, nowId отфильтровал идентификатор, где id === this.state.initialVal и отобразил его
в Render, при клике NavLink, он изменяет значение initialVal (функция ChoseSeason)
Все работает нормально, но иногда при нажатии (может быть после 2-го или 100-го щелчка) кнопка переходит к initialValue, из-за чего мой компонент ничего не отображает. (на картинке ниже при 10-м щелчке ничего не проходит)
Это как-то связано с моей логикой/синтаксисом? пожалуйста помоги! Спасибо!
Вы можете передать идентификатор в метод ChooseSeason и обновить состояние
constructor(props) {
super(props);
this.state = {
collections: [],
collection: [],
initialVal: [],
};
choseSeason = id => {
// console.info(id);
this.setState({
initialVal: id,
}, () => console.info('initialVal: '+this.state.initialVal));
}
componentDidMount() {
axios.get(`https://myapi`)
.then(res => {
const collections = res.data;
this.setState({
collections,
collection: collections.map(collection=>(collection)),
//this is console log line 29
initialVal: collections[0].id,
});
})
}
render() {
const { collections = [] } = this.state;
const collection = this.state;
const nowId = collections.filter(collection => collection.id ===
this.state.initialVal);
console.info(nowId); //this is console log line 56
return (
<Container className = "collection">
<div className = "">
{collections.length ? collections.map(c=>(
<div className = "nav"><NavLink activeClassName = {"active3"} onClick = {()=>this.choseSeason(c.id)}><span id = {c.id}>{'SS'+c.name.slice(7, 9)}</span></NavLink></div>
))
:
<React.Fragment/>
}
</div>
{nowId.length ?
<div className = "wrapper">
<div className = "item1 flex">
<div className = "flex right">
<div className = "title vBot">
{nowId[0].collection_titles[0].title}
</div>
</div>
...
Не могли бы вы поделиться рабочим фрагментом кода?