我試圖設置一個React應用程序,其中單擊某個組件中的地圖標記時,將使用數據庫中的數據重新呈現頁面上的另一個組件並更改URL。它工作,有點,但不好。 我無法弄清楚從Redux獲取狀態並從API獲取響應是否適合React生命週期。使用API調用更新React-Redux中的組件狀態
有兩個相關的問題:
優先:註釋掉的行「//APIManager.get()......」不工作,但就行了黑客攻擊,一起版本在它下面。
SECOND:我在console.log()中的行 - 無限的響應日誌,並向我的數據庫發出無限的GET請求。
這裏是我下面的成分:
class Hike extends Component {
constructor() {
super()
this.state = {
currentHike: {
id: '',
name: '',
review: {},
}
}
}
componentDidUpdate() {
const params = this.props.params
const hack = "/api/hike/" + params
// APIManager.get('/api/hike/', params, (err, response) => { // doesn't work
APIManager.get(hack, null, (err, response) => { // works
if (err) {
console.error(err)
return
}
console.log(JSON.stringify(response.result)) // SECOND
this.setState({
currentHike: response.result
})
})
}
render() {
// Allow for fields to be blank
const name = (this.state.currentHike.name == null) ? null : this.state.currentHike.name
return (
<div>
<p>testing hike component</p>
<p>{this.state.currentHike.name}</p>
</div>
)
}
}
const stateToProps = (state) => {
return {
params: state.hike.selectedHike
}
}
export default connect(stateToProps)(Hike)
另外:當我點擊頁面上的鏈接轉到另一個URL,我得到以下錯誤:
"Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op."
它使你的數據庫無限通話,因爲你調用'componentDidUpdate'的API,然後從API的響應,這會導致'componentDidUpdate'鉤再次觸發重新設置狀態。 –