【问题标题】:add AVATAR url promise添加 AVATAR 网址承诺
【发布时间】:2020-10-14 19:45:22
【问题描述】:

我想创建待办事项应用程序,该应用程序为每个项目添加来自 npm liberty ("@dudadev/random-img") 的随机图像,该图像返回承诺。 只在第一次之后才起作用,这意味着我创建的第一个项目将没有图像,并且在它将工作并创建图像之后(附上示例截图)

class App extends Component {
  state = {
    // load items while initializing
    items: [],
    id: uuidv4(),
    item: "",
    image: "image here",
    editItem: false
  };
  
  componentDidMount(){
    const localStorageList = window.localStorage.getItem('items') ? JSON.parse(window.localStorage.getItem('items')) : [];
    if (!localStorageList){
      return null;
    } 
    else {
      this.setState({items: localStorageList})
    }
  }
  handleChange = e => {
    ...
  };
  handleSubmit = e => {
    e.preventDefault();
    imgGen().then(avatarURL => this.setState({ image:avatarURL }))
    const newItem = {
      id: this.state.id,
      title: this.state.item,
      image: this.state.image
    };
    const updatedItems = [...this.state.items, newItem];
    // Save items while changing
    localStorage.setItem('items', JSON.stringify(updatedItems));

    this.setState({
      items: updatedItems,
      item: "",
      image: "image here",
      id: uuidv4(),
      editItem: false,
    });
    
  };

  clearList = () => {
    ...

  };
  handleDelete = id => {
    ...

  };
  handleEdit = id => {
    ...
  };

  render() {
    return (
            <TodoInput
              item={this.state.item}
              handleChange={this.handleChange}
              handleSubmit={this.handleSubmit}
              editItem={this.state.editItem}
            />
            <TodoList
              items={this.state.items}
              clearList={this.clearList}
              handleDelete={this.handleDelete}
              handleEdit={this.handleEdit}
            />
}

【问题讨论】:

    标签: javascript reactjs promise


    【解决方案1】:

    promise 是异步的,因此在您将新项目添加到列表时它还没有更新组件状态;换句话说,当您使用/设置updatedItems 时,this.state.image 仍然是"image here"。因此,每个后续项目实际上都在使用上一个提交返回的图像。

    您应该在 .then 中移动更多代码,以便它仅在您返回图像时添加项目。

    【讨论】:

    • 如果我将所有其余的功能代码插入到 .then 没有任何作用
    • 我不明白为什么它不会。你需要更新你的代码,这样你的图像就不是来自状态;它不再需要了。
    猜你喜欢
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2014-03-20
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多