我在我的应用程序中使用了材料下拉列表
<Dropdown
baseColor='white'
itemColor='white'
label='Select Cluster'
/>
我像这样获取JSON对象,它工作正常 .
fetch('url', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username : "admin"
})
}).then((response) => response.json())
.then((responseJson) => {
var count = Object.keys(responseJson.message.Obj).length;
for(var i=0;i<count;i++){
console.log(responseJson.message.Obj[i].name) // I need to add
//these names to dropdown
}
})
.catch((error) => {
console.error(error);
});
现在我需要将responseJson.message.Obj [i] .name值添加到我的下拉列表中 .
4 回答
假设您正在使用react-native-material-dropdown .
Example:
Dopdown
组件:请求代码:
Doc:
React native state management
react-native-material-dropdown
您可以通过使用react native“state”来实现此目的 . 创建一个状态,然后将其分配给Dropdown组件的数据属性 . 然后使用“this.setState()”方法将responseJson.message.Obj [i] .names设置为state .
找出您正在使用的
<Dropdown />
组件所需的data
属性的形状(即对象数组)在
componentDidMount
内进行抓取调用将组件的
state
视为不可变(不要直接push
到this.state. dropdownData
)以下是使用react-native-material-dropdown的示例代码:
见:AJAX Requests in React
见:react-native-material-dropdown expected data type
你也可以采取这样的方法:
您现在可以使用一些选项来设置状态 . 从您的示例中,您可以将列表状态设置为一旦呈现后从fetch调用返回的数据 . 需要记住的一件事是,react目前不支持异步加载 . 因此,数据必须呈现为空,或者使用一些示例数据,然后在调用任何您想要更新的内容后更新!希望这有点帮助:) https://reactjs.org/docs/faq-ajax.html