javascript - 通过映射到子 html 元素呈现响应数据...使用 React 和更新状态

标签 javascript json reactjs

我正在尝试通过生成的映射数组显示响应数据,以响应子元素 (innerHTML)。我目前正在输出 null 作为数据,即使我在响应 header 中看到了真实数据。

这是查找函数

 lookup = () => {
    console.log('Step 1. Smartystreets - Define Lookup.');
    let lookup = new Lookup();
    lookup.street = this.state.shippingAddress.addressLine1;
    lookup.street2 = this.state.shippingAddress.addressLine2;
    lookup.city = this.state.shippingAddress.city;
    lookup.state = this.state.shippingAddress.state;
    lookup.zipCode = this.state.shippingAddress.zipCode;
    lookup.match = 'strict';
    lookup.maxCandidates = 1;

    console.log('Step 2. Send the lookup to smartystreets.');
    client.send(lookup)
    .then((response) => {
      console.log('Step 3. Show the resulting candidate addresses:');
      console.dir(response);
      response.lookups[0].result.map(this.buildTextOutput);
    })
    .catch((response) => {
      console.warn(response);
    });
 }
 buildTextOutput = () => {
  const candidateOutput = document.getElementById("verifiedAddress");
  const outputElement = document.createElement('verifiedAddressResults');
  outputElement.innerHTML = candidate.deliveryLine1 + '<br>' + candidate.lastLine;

  candidateOutput.appendChild(outputElement);
}  
}

我需要将 candidate.deliveryLine1 + candidate.lastLine 输出为 react 友好的,这样我就可以向用户提供一个选项来选择输出结果作为地址,并将 setState 作为新的响应数据...我认为我很漂亮关闭...有什么帮助吗?

最佳答案

首先,我建议避免使用诸如 .innerHTML 之类的方法直接操作 DOM - React 在单独使用时可以很好地区分和高效地呈现页面,但如果您意外修改,则可能会遇到困难像这样的 DOM。

至于你的问题,我会保存对组件状态的响应,然后像这样内联映射数据:

// in lookup function
client.send(lookup)
    .then((response) => {
      console.log('Step 3. Show the resulting candidate addresses:');
      console.dir(response);
      this.setState({addresses: response.lookups[0].result})
    })

// in render function
{this.state.addresses.map((address) => {
    return (
        // Desired markup here
    )
})}

关于javascript - 通过映射到子 html 元素呈现响应数据...使用 React 和更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800731/

相关文章:

javascript - typescript + Angular : variable changing context

javascript - 按自定义顺序显示 DIV

javascript - Ember.js - 使用 removeObject 仅删除对象的一个​​实例

javascript - Angular JS 在 django 中转换 2 个暗淡的 JSON

arrays - 解析服务器发送的数组/slice

reactjs - Redux 路由器未捕获类型错误 : createHistory is not a function

javascript - React Router 路由深度为三层,仅适用于 App.js 文件

javascript - 对多个选择框上的 selectedOptions 使用一个选项列表进行 knockout

javascript - Not a Legal JSONP API -- 如何在没有 CALLBACK 参数的情况下获取数据

javascript - 如何在导航到不同页面之前执行 onclick?