【问题标题】:Cloning Dictionaries in React JSX在 React JSX 中克隆字典
【发布时间】:2020-10-15 22:10:45
【问题描述】:

我很难找到这个问题的答案。假设我有以下脚本(不起作用):

class ProfileCard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: {},
    };
  }

  componentDidMount() {
    fetch("/accounts/api/" + username)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }
}

这分别是resultthis.state.items 的样子:

{last_login: "2020-06-25T09:50:24.218Z", is_superuser: "true", is_staff: "true", …}
{}

如何使this.state.itemsresult 具有完全相同的内容?请假设所有使用的变量和方法都已声明。

【问题讨论】:

  • 你所拥有的对我来说看起来不错。也许您正试图在数据可用之前访问this.state.items?请提供一个完整的例子。

标签: reactjs dictionary ecmascript-6 jsx


【解决方案1】:

你好吗? 你的渲染()怎么样?你能详细说明你的问题吗? 对我来说,将结果放入项目中的方式是正确的,但它只设置状态并在渲染后更改项目的内容。 下面是一个例子:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      image: ''
    }
    this.urlImage = this.urlImage.bind(this);
  }

  urlImage() {
    fetch("https://dog.ceo/api/breeds/image/random")
      .then( (res) => res.json())
      .then((results) => this.setState({ image: results }))
  }


  componentDidMount() {
    this.urlImage()
  }

  render() {
    const { image } = this.state;
    if (image === '') return <h2>Loading...</h2>
    return (
      <div>
        <h2>Dogs!</h2>
        <div>
        <img src={image.message} alt={'Dog'}/>
        </div>
      </div>
    );
  }
}

很抱歉,如果您理解我没有正确解释您的问题,但想补充使用 render() 作为示例来表明 this.setState() 是异步的,因此您可以使用 render() 进行此更改状态,或者您可以使用同样在状态中执行的 componentDidUpdate() 接收新值。

componentDidUpdate () {
  console.log (this.state.items)
}

https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

其实你需要更好地指定一个问题,因为一个简单的“我的状态是这样的,我希望它可以是这样的”这个没有描述,我希望你能做你想做的事。谢谢!

【讨论】:

  • 就我个人而言,我认为插入渲染函数不会有帮助,因为这不是我对这个问题的重点,因为我只想复制字典对象。第二件事是我想克隆一个 dictionary,而不是一个字符串。非常感谢您的帮助,但请下次先清楚阅读问题。
猜你喜欢
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
  • 2012-10-09
  • 2021-09-16
  • 1970-01-01
  • 2020-04-15
  • 2023-02-02
  • 1970-01-01
相关资源
最近更新 更多