【问题标题】:Cannot retrieve single item from an array stored in the state of React无法从存储在 React 状态的数组中检索单个项目
【发布时间】:2019-02-07 20:35:12
【问题描述】:

在我被抨击之前:“我是 React 新手!”

.json 文件的 url 是:

JSON FOR GETTING QUOTES

我在我的应用程序中维护一个状态,该状态包含一个引号数组和其中的键值。

constructor(props){
    super(props);
    this.state = {
        quotes: [],
        key: 0
    };
    this.handleClick= this.handleClick.bind(this)
}

状态在使用 axios 获取对 url 的请求时更新。

 componentDidMount() {
    const url = 'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json';

    axios.get(url).then((res) =>{
        const items = (res.data.quotes)
        this.setState({quotes: items})
        console.log(this.state)
    }).catch(err => console.log(err))
}

然后我希望每次点击按钮时只获得一个报价。 为此,我渲染了一个“DivElement”,将特定的引号作为道具传递如下:

render() {
    return (
        <div>
        <button onClick={this.handleClick}>
            Click Me
        </button>
        <DivElement
        currentquote = {this.state.quotes[this.state.key].quotes}
        />
        </div>
    );
}

“DivElement”声明:

function DivElement(props){
console.log(props.currentquote)
return <p>{props.currentquote}</p>}

这是我得到的 TypeError:

TypeError: this.state.quotes[this.state.key] is undefined

我尝试过的事情:

不起作用使用 JSON.parse 方法设置状态。

我想做什么:根据 onClick 方法生成的随机密钥显示随机报价。

【问题讨论】:

    标签: javascript arrays json reactjs axios


    【解决方案1】:

    没有渲染是异步的,它不等待 API 回调。


    你必须像这样有条件地渲染你的组件:

     render() {
        return (
          this.state.quotes.length && ( <div>
              <button onClick={this.handleClick}>
                Click Me
              </button>
              <DivElement
                currentquote={this.state.quotes[this.state.key].quotes}
              />
          </div> )
        );
      }
    }
    

    如果问题仍然存在,请告诉我,

    【讨论】:

    • 希望对此处的“&&”运算符进行解释。
    • 您遇到了什么错误,请分享?除非您的引号长度大于 1,否则 && 之后的代码块将不会被呈现
    • ./src/App.js 语法错误:C:/Users/Dell/Documents/Freecodecamp Projects/random_quote_machine/src/App.js:相邻的 JSX 元素必须包含在封闭标记中(55 :16) 53 |点击我 54 | 按钮>> 55 |
      58 | }
    • 可能在 App.js 中的 DivElement 中缺少结束标记,而不是在这里您应该检查您的代码。或者你可以在这里分享codeandbox以便更好地理解
    • 非常感谢!现在就像一个魅力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    相关资源
    最近更新 更多