【发布时间】:2021-08-04 14:06:53
【问题描述】:
我正在尝试根据搜索查询加载图像并能够拖动它们。例如,当我输入“猫”这个词时,我可以看到猫的图片。 这是输入搜索词的代码:
<input type="text" value={this.state.searchedValue} onChange={(e)=>{this.setState({searchedValue: e.target.value})}}/>
<button onClick={() => this.handlePress()}>Search</button>
这是根据搜索查询加载图像并将其放入数组中的函数
handlePress = async () => {
console.log("function is called");
fetch('http://localhost:5000/testData?title_picture=' + this.state.searchedValue, {
"method": "GET"
})
.then((response) => response.json())
.then((responseData) => {
this.setState({newData: responseData,
loaded:true})
console.log(this.state.newData);
})
}
这是加载图片
{this.state.newData.map((data) => (
<div class="dragImg">
<img src={data.picture} class="img"/>
</div>
))}
当我在handlePress 函数内执行控制台日志时,我可以看到数组内有一张图片。
但是当我在ComponentDidMount() 中执行此操作时,它会显示一个空数组。我该如何解决这个问题?不能为空数组,否则无法将图片拖到画布上。
【问题讨论】:
-
ComponentDidMount 将在您的组件第一次在 DOM 中加载时调用,我认为第一次您的数组将是空白的。搜索后看到图片了吗?
-
图片已显示。但是数组是空的。为了能够在 div class="dragImg" 中被拖动,它不能是空数组。
-
如果图像确实出现了,那么数组怎么可能是空的?您正在显示来自数组数据的图像吗?
-
Handlepress 函数中的数组不是空的。但是在 ComponentDidMount 函数中它是空的。因此,我无法拖动图片。
-
ComponentDidMount 中的空数组是预期的,因为您通过 API 调用获取数据。如果您不能有一个空数组,请在您的组件的 construction(){} 上添加一些占位符图像。
标签: javascript arrays reactjs react-native