使用基于API调用的props渲染组件?

时间:2020-01-10 05:19:37

标签: reactjs axios

最近,在Promise不断破坏该Component的情况下,尝试使Component与通过API调用传递的道具一起使用时遇到了一些麻烦。有没有办法让Component的执行等到Promise履行完毕,还是有其他方法可以处理这种情况?

在这种情况下,无法设置UserData的{​​{1}}属性,因为Promise是作为未定义的(userImage)传递的。

这是我的主要组成部分

TypeError: Cannot read property 'user_id' of undefined

这是export default class Player extends Component { constructor(props) { super(props) this.state = { playerName: "Catulus", gamemode: 1, playerData: null, playerBest: null } this.fetchAPI = this.fetchAPI.bind(this) this.fetchUser = this.fetchUser.bind(this) } fetchAPI(event) { event.preventDefault() this.fetchUser().then(result => { this.setState({ playerData: <UserData info={this.state.playerData}/>, }) }) } fetchUser() { const userUrl = apiLink + userData + apiKey + "&u=" + this.state.playerName + "&m=" + this.state.gamemode + "&type=string" return axios.get(userUrl) } render() { return ( <div> <div className="Subtitle"> <form onSubmit={this.fetchAPI} style={{position: "relative", width: "100%"}}> <span style={{margin: "auto auto auto 0"}}>Search by player</span> <span className="fas fa-search"></span> <input name="username" type="text" placeholder="username" defaultValue={this.state.playerName} /> <select name="mode" defaultValue= "1"> <option value="0">osu!</option> <option value="1">osu!taiko</option> <option value="2">osu!catch</option> <option value="3">osu!mania</option> </select> <input type="submit" value="Search" id="SubmitButton" /> </form> </div> {this.state.playerData} </div> ) } } 组件

UserData

此处未显示的所有变量均已正确定义。正确方向的任何建议或指南都将非常有帮助。预先感谢!

1 个答案:

答案 0 :(得分:0)

不要在状态中存储整个组件。仅存储渲染它们所需的信息。另外,您没有使用获取的结果,并且状态也只是引用自身(因为它是一个以状态为道具的组件)。

您将想要执行以下操作:

    this.setState({
      playerData: result.data    // store data from result object in state
    })

,然后在数据存在时渲染组件:

{
    this.state.playerData === null ?
    "Loading player data..." :
    <UserData info={this.state.playerData} />
}