我需要在人们搜索位置时创建一个按钮.

错误Can't find variable: addToResult

class NewCampaign extends React.Component {
    construc到r(props) {
        super(props);
        this.state = {
          value: null
        };
      }
    
  
    


    render(){
        var currentTimeoutId;
        var areas = [];

       
        function addToResult(e){
            areas.push(e);
        }

        function checkAnswer(event, e) {
    
            if(currentTimeoutId){
                clearTimeout(currentTimeoutId);
             }
         
             currentTimeoutId = setTimeout(function(){
                 currentTimeoutId = null;
                    axios.get('https://nominatim.openstreetmap.org/search.php?city='+e+'&countrycodes=AU&featuretype=county&polygon_geojson=1&format=json')
                    .then(function (response) {
                    // handle success
                    document.getElementById("results").innerHTML = "";
                    for (let i = 0; i < response.data.length; i++) { 
                        document.getElementById("results").innerHTML +="<but到n onClick={addToResult("+response.data[i].osm_id+")}>ID:"+response.data[i].osm_id+" - "+response.data[i].display_name+"</but到n>\n\n"
                    }
        
                    })
                    .catch(function (error) {
                    // handle error
                    console.log(error);
                    })
                    .then(function () {
                    // always executed
                    });
                },1000);
        
        }
        return (
            <React.Fragment>
                <div>
            <input name="search" id="search" placeholder='Suburbs'
             value={this.state.value}
             onChange={e => {this.setState({ value: e.currentTarget.value})}}
             onKeyUp={(event) => {checkAnswer(event, this.state.value)}} />
            <div id="results"></div>
            <div id="debug"></div>
             
       
            </div></React.Fragment>  );
    }
}

export default NewCampaign;

经过更多的研究,我发现我需要做如下的事情

    checkAnswer = (event, e) => {
        if(currentTimeoutId){
            clearTimeout(currentTimeoutId);
         }
     
         currentTimeoutId = setTimeout(function(){
             currentTimeoutId = null;
             alert(e)
                axios.get('https://nominatim.openstreetmap.org/search.php?city='+e+'&countrycodes=AU&featuretype=county&polygon_geojson=1&format=json')
                .then(response => {
                    console.log(response);
                    return response.data.map(user => ({
                      Id: `${user.osm_id}`,
                      name: `${user.place_id}`,
                      Company: `${user.display_name}`,
                    }))
                  })
                      .then(users => {
                        this.setState({
                          users,
                          isLoading: true
                        });
                      })
                  .catch(function (error) {
                // handle error
                console.log(error);
                })
                .then(function () {
                // always executed
                
                //alert(response)
                });
            },1000);
    
    }   

然而我仍然在

TypeError: _this.setState is not a function. (In '_this.setState({
                        users: users,
                        isLoading: true
                    })', '_this.setState' is undefined)

不管我是怎么定义的

   construc到r(props) {
        super(props);
        this.state = {
          value: null,
          users: [],
          isLoading: false
        };
      }

注:如果它在emits 时是自动装载机,我就可以让它工作

https://codepen.io/redimongo/pen/dydNbGX?edi到rs=1111

这是一个简单的解决办法

我变了

currentTimeoutId = setTimeout(function(){

currentTimeoutId = setTimeout(() => {

推荐答案

错误是由以下代码引起的:

"<button onClick={addToResult("+response.data[i].osm_id+")}>ID:"+response.data[i].osm_id+" - "+response.data[i].display_name+"</button>\n\n"

我建议您制作另一个组件来呈现"addToResult"和内部内容,而不是使用".innerHTML"

一个可能的好方法是为数据获取的结果设置一个状态:

const [results,setResults] = useState([]);

然后,可以使用自定义按钮渲染每个结果:

const Button = ({onClick, children}) => <button onClick={onClick}>{children}</button>

稍后,在渲染部分,只需映射结果并将其显示为:

{results.map(result => <Button onClick={}>{result.osm_id}</Button>}

Javascript相关问答推荐

如何指定1条记录1个表?

用相器进行向内碰撞检测

使用TMS Web Core中的HTML模板中的参数调用过程

如何访问Json返回的ASP.NET Core 6中的导航图像属性

Rehype将hashtag呈现为URL

google docs boldText直到按行执行应用脚本错误

使用useEffect,axios和useParams进行react测试

使用JQuery单击元素从新弹出窗口获取值

JSDoc创建并从另一个文件导入类型

为什么useState触发具有相同值的呈现

覆盖TypeScrip中的Lit-Element子类的属性类型

TypeError:无法分解';React2.useContext(...)';的属性';basename';,因为它为空

禁用.js文件扩展名并从目录导入隐式根index.js时,找不到NodeJS导入模块

如何将未排序的元素追加到数组的末尾?

使用Nuxt Apollo在Piniastore 中获取产品细节

如何在 Select 文本时停止Click事件?

Next.js中的服务器端组件列表筛选

匹配一个或多个可选重复的特定模式

将嵌套数组的元素乘以其深度,输出一个和

使用可配置项目创建网格