我正在尝试通过生成的映射数组显示响应数据,以响应子元素 (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/