![](/img/trans.png)
[英]Trying to bind data to state with input field that's being mapped in React
[英]React JSON mapped data. Trying to pass a setState variable from mapped function will not get the latest state on render
我正在研究 React SPA 並嘗試使用過濾器呈現 JSON 數據。 我有幾個容器,每個容器都有一個類值。 單擊容器時,我試圖將值傳遞給 setState。 但是,當退出地圖功能時,我無法更新新的狀態更改。
我假設渲染狀態沒有為該狀態更新。
import React, { Component } from "react";
import ListData from "../data/list.json";
class Levels extends Component {
constructor(props) {
super(props);
this.state = { newFilter: "" };
this.onClick = this.setFilter.bind(this);
}
setFilter = e => {
console.log(e); //This returns the correct class.
this.setState({ newFilter: e }); //This will not update
};
render() {
console.log(this.state.newFilter); //This just returns the initial state of ''
const activeTab = this.props.keyNumber;
let levelFilter = ListData.filter(i => {
return i.level === activeTab;
});
let renderLevel = levelFilter.map((detail, i) => {
let short_desc;
if ((detail.short || []).length === 0) {
short_desc = "";
} else {
short_desc = <p>{detail.short}</p>;
}
return (
<div
className={`kr_sItem ${detail.class}`}
data-value={detail.class}
onClick={() => this.onClick(detail.class)}
value={detail.class}
key={i}
>
<h1>{detail.title}</h1>
{short_desc}
<img src={`${detail.img}`} />
</div>
);
});
console.log(this.state.newFilter);
return (
<div id="kr_app_wrapper">
<div id="lOneWrapper">{renderLevel}</div>
<div id="lTwoWrapper"></div>
</div>
);
}
}
export default Levels;
這是在組件中調用的代碼:
import React, {Component} from 'react';
import Levels from './components/levels2';
import {
Route,
NavLink,
HashRouter
} from "react-router-dom";
import LevelTwo from "./levelTwo";
class LevelOne extends Component{
render(){
return(
<div id="lOneWrapper">
<NavLink to='/Level2'><Levels keyNumber={1} /></NavLink>
</div>
)
}
}
export default LevelOne;
編輯:正如評論中所指出的,綁定一個箭頭函數是沒有意義的,但它不會在這里導致錯誤,所以在你的代碼的其他部分肯定有其他事情發生。
問題是您正在嘗試綁定一個沒有隱式this
的箭頭函數。 要么直接調用setFilter
(無需將this
與箭頭函數綁定)或將setFilter
函數更改為常規函數:
class Levels extends Component{
constructor(props){
super(props);
this.state = {newFilter: ''};
this.onClick = this.setFilter.bind(this);
}
setFilter(e) {
console.log(e); //This returns the correct class.
this.setState({newFilter: e}); //This will not update
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.