【问题标题】:How to store a value of prop in a variable and then access it in react?如何将 prop 的值存储在变量中,然后在反应中访问它?
【发布时间】: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 的值

标签: json ajax reactjs axios


【解决方案1】:

使用 axios 您正在发出请求。这意味着您的 JSON 将从端点提供。如果你真的需要这种方式的 json 文件,请尝试导入

import abc from './abc.json';

componentDidMount = () => {
 this.setState({
 json: abc 
 })
}

【讨论】:

  • 我正在使用 cdn 进行反应
  • 我实际上希望首先从第一个 json 文件中获取 apiKey,然后在它的帮助下我想从第二个 json 文件中获取 src 的值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-28
  • 1970-01-01
  • 2016-07-13
  • 2015-01-31
  • 2015-09-01
相关资源
最近更新 更多