試圖顯示過濾表,但不成功,見下文。
閱讀地圖時不斷收到未定義的錯誤,似乎無法弄清楚為什么在呼叫時沒有通過大學 filteredColleges.map(college)
這可能是因為我正在呼叫<Table/>內部的組件App.js并忘記了一個基本步驟嗎?
App.js 看起來像這樣:
return (
<div className="App">
<header className="App-header">
<h1>Partners</h1>
<Table/>
</header>
</div>
);
}
如果有人可以幫助我,我將非常非常感激。提前致謝!
import React , {Component } from 'react'
export default class Table extends Component {
// Display API data - componentDidMount - pull specific elements - DONE
// Create table displaying API data
// Create Search bar
// Create drop down list for prefix
// Style Ofsted Rating column
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
colleges: [],
searchByName: ""
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ searchByName: event.target.value });
}
componentDidMount() {
fetch(`https://collegesapi/data.json`)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
colleges: result.getColleges
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
renderRow(college) {
return (
<tr key={college.id}>
<td>{college.name}</td>
<td>{college.groupPrefix}</td>
<td>
{college.logo && (
<img className="w-full" src={college.logo} alt={college.name} />
)}
</td>
<td>{college.ofstedRating}</td>
</tr>
)
}
render() {
const filterColleges = (colleges, query) => {
if(!query) {
return colleges;
}
return colleges.filter((college) => {
const collegeName = college.name.toLowerCase();
return collegeName.includes(query);
});
};
const filteredColleges = filterColleges(
this.props.colleges,
this.state.searchByName
);
const { error, isLoaded, colleges } = this.state;
if (error) {
return <div>Error: {error.message}</div>
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
<table className="table-fixed border-collapse">
<thead>
<tr>
<input
type="text"
placeholder="Search partners"
onChange={this.handleChange}
/>
</tr>
<tr>
<th className="w-1/12">Partner</th>
<th className="w-1/12">Prefix</th>
<th className="w-1/12">Logo</th>
<th className="w-1/12">Ofsted Rating</th>
</tr>
</thead>
<tbody>{filteredColleges.map((college) => this.renderRow(college))}</tbody>
</table>
</div>
)
}
}
}
uj5u.com熱心網友回復:
您在發送到“filterColleges”函式時指的是 this.props.colleges:
const filteredColleges = filterColleges(
this.props.colleges,
this.state.searchByName
);
相反,由于您在從 API 回應收到時將其設定為狀態,因此您應該相應地參考:
const filteredColleges = filterColleges(
this.state.colleges,
this.state.searchByName
);
此外,處理錯誤或空回應總是好的,例如,如果您的 API 甚至不回傳空陣列,那么此代碼仍然會拋出相同的錯誤。因此,您可以在這些情況下添加空合并檢查 (??) 并分配空陣列,如下所示:
this.setState({
isLoaded: true,
colleges: result?.getColleges ?? [],
});
希望能幫助到你!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/310802.html
標籤:javascript 反应 搜索
