我试图通过react从我的节点后端调用一个对象,但是我试图基于一个字符串来调用对象。因此,如果字符串是'Cat',我希望访问Cat对象和它下面的任何其他键/值。
代码的示例如下:
componentDidMount() {
let catName = 'Cat' //this string is actually passed in
this.callApi()
.then(res => this.setState({ catsName: res.catName.name }))
//catsName: res.Cat.name works
.catch(err => console.log(err));
}
callApi = async () => {
//lets say this example route has all animals in the world as objects
const response = await fetch('/animals');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
};我知道它不工作,因为它是一个字符串,但试图同时转换字符串或对象也没有工作。我的节点知识有限,有什么建议或线索吗?或者这根本不可能,我认为这是错误的?提前谢谢。
如果有帮助的话,这个示例的节点后端是什么样子的。所有动物的api文件(名称、年龄、食草动物等)都有关键值:
app.get('/animals', (req, res) => {
res.send({ Cat, Dog, Cougar, Wolf, etc.... });
});发布于 2018-01-23 12:50:49
发布于 2018-01-23 12:50:35
你需要数组表示法。
res[catName].name发布于 2018-01-23 12:50:38
将res.catName.name转换为res[catName].name
https://stackoverflow.com/questions/48402136
复制相似问题