【发布时间】:2019-07-14 03:29:01
【问题描述】:
我正在使用 cdn 进行反应
其实我有两个 JSON FILE,
abc.json
[
{
"apiKey":"642176ece1e7445e99244cec26f4de1f"
}
]
reactjs.json
[
{
"642176ece1e7445e99244cec26f4de1f": {
"src": "image_1.jpg",
"id" : "1"
}
}
]
我实际上想要首先从第一个 json 文件中获取 apiKey,然后在它的帮助下我想获取 src 的值
1) 我如何在 React 中使用 axios 做到这一点? 2)我们可以直接从 reactjs.json 获取 src 吗?如果是,那么如何?
我试过了,但它给出了错误..
class FetchDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
images: [],
api:[]
};
//this.listImages = this.listImages.bind(this);
}
componentDidMount() {
axios.get('abc.json').then(res => {
console.log(res);
this.setState({ api: res.data });
});
axios.get('reactjs.json').then(res => {
console.log(res);
this.setState({ images: res.data });
});
}
render() {
return (
<div>
{this.state.api.map((api, index) => (
<Pictures key={index} apikeys={api.apiKey} />
))}
</div>
);
}
}
class Pictures extends React.Component {
render() {
return (
<h1>
alt={this.props.apikeys}
</h1>
{this.state.images.map((images, index) => (
<h1 key={index}> apikeys={images.+`{this.props.apikeys}`+.src} </h1>
//Error at this point
))}
);
}
}
ReactDOM.render(
<FetchDemo/>,
document.getElementById("root")
);
【问题讨论】:
-
你在使用 webpack 吗?如果是这种情况,您可以只导入您的 JSON 文件。您的 JSON 也是其中包含一个对象的数组。看起来你可以直接把它们变成对象,让自己更容易。
-
我实际上希望首先从第一个 json 文件中获取 apiKey,然后在它的帮助下我想获取 src 的值