【发布时间】:2019-06-02 06:58:11
【问题描述】:
我遇到了这种情况,我有一个下拉菜单,可以拉出用户的帐户,然后根据其选择更改页面内容。我正在尝试一种如下所示的方法,似乎 setState 没有被正确调用,或者调用序列可能是错误的。没有真正得到什么是错的。更改下拉值不会更新内容。
我们将不胜感激。
import * as React from 'react';
import Select from 'semantic-ui-react/dist/commonjs/addons/Select';
interface IState{
accountDetails[], // stores all details w.r.t an account
userAccounts: [], // stores all accounts w.r.t a user
selectedAccount : string, // selected account from the dropdown
[x: string] : any,
}
export default class App extends React.Component<{},IState> {
constructor(props:any){
super(props);
this.state = {
accountDetails: [],
userAccounts: [],
selectedAccount: ''
}
}
dropdownChange = (event: React.SyntheticEvent<HTMLElement>, data:any) => {
this.setState(prevState => ({
selectedAccount: data.value
}), () => {});
}
async componentDidMount()
{
await this.fetchUserAccounts();
}
fetchUserAccounts = async() => {
//fetch API call for getting all user accounts by passing a user ID
// I am able to get the data
fetch('/api/fetch/accounts'
.then(response => response.json())
.then(data => this.setState({ userAccounts: data}));
this.fetchAccountDetails();
}
fetchAccountDetails = async() =>
{
let URL = "/api/fetch/account?accountId=" +this.state.selectedAccount;
fetch('URL'
.then(response => response.json())
.then(data => this.setState({ accountDetails: data}));
}
render() {
return(
<div>
<Select
options={this.state.userAccounts}
name="selectedAccount"
value={this.state.selectedAccount}
onChange={this.dropdownChange}
/>
// component to display the details
<DetailComponent accounts={this.state.accountDetails} />
</div>
)
}
}
【问题讨论】:
-
当下拉列表发生变化时,您不会再次调用
fetchAccountDetails函数来获取帐户详细信息。
标签: reactjs typescript setstate semantic-ui-react