如何在React中使用键/值对象

时间:2019-02-19 23:51:41

标签: javascript reactjs gun

我正在努力利用对象来做出反应,我正在尝试访问所返回的key:value(并且我可以成功地console.log)。

我尝试过的所有示例都导致映射每个字符或引发对象子错误,这让我感到茫然。

  componentDidMount() {
    this.gun.on('auth', () => this.thing());
  }

  thing() {
    this.gun.get('todos').map((value, key) => { console.log(key, value) }
    );
  }

  handleChange = e => this.setState({ newTodo: e.target.value })

  add = e => {
    e.preventDefault()
    this.gun.get('todos').set(this.state.newTodo)
    this.setState({ newTodo: '' })
  }

  del = key => this.gun.get(key).put(null)

  render() {
    return <>
      <Container>
        <div>Gun</div>
        <div>
          <form onSubmit={this.add}>
            <input value={this.state.newTodo} onChange={this.handleChange} />
            <button>Add</button>
          </form>
          <br />
          <ul>
            {this.state.todos.map(todo => <li key={todo.key} onClick={_ => this.del(todo.key)}>{todo.val}</li>)}
          </ul>
        </div>
      </Container></>
  }
}

1 个答案:

答案 0 :(得分:1)

有几种方法可以将组件状态与另一个数据源(即gun对象)同步-一种简单的方法是缓存计划呈现的todo数据的副本,在组件的state中。

这是通过setState()函数完成的,该函数在调用时将导致组件重新呈现。对于组件的render()方法,更改todos状态字段将更新列表以显示。

使用这种方法,您需要确保在更改gun对象的待办事项数据时,还通过todo更新组件setState()状态,如下所示:

constructor(props) {
    super(props)

    /* Setup inital state shape for component */
    this.state = {
        todos : [], 
        newTodo : ''
    }
}

mapTodos() {
    return this.gun.get('todos').map((value, key) => ({ key : key, val : value }));
}

componentDidMount() {
    this.gun.on('auth', () => this.mapTodos());
}

handleChange = e => this.setState({ newTodo: e.target.value })

add = e => {
    e.preventDefault()
    this.gun.get('todos').set(this.state.newTodo)

    /* When adding a todo, update the todos list of the component's internal state
    to cause a re-render. This also acts as a cache in this case to potentially speed
    up render() by avoiding calls to the gun.get() method */
    this.setState({ newTodo: '', todos : this.mapTodos() })
}

del = key => {
    this.gun.get(key).put(null)

    /* Call setState again to update the todos field of the component state to
    keep it in sync with the contents of the gun object */
    this.setState({ newTodo: '', todos : this.mapTodos() })
}

render() {
    return <Container>
        <div>Gun</div>
        <div>
            <form onSubmit={this.add}>
            <input value={this.state.newTodo} onChange={this.handleChange} />
            <button>Add</button>
            </form>
            <br />
            <ul>
            {this.state.todos.map(todo => <li key={todo.key} onClick={ () => this.del(todo.key) }>{todo.val}</li>)}
            </ul>
        </div>
    </Container>
}