Как установить новое состояние локали из наблюдаемого массива в React? - PullRequest
0 голосов
/ 30 апреля 2019

У меня есть исходный массив: 1, 2, 3, 4, 5, и я хочу добавить 1 к каждому элементу в массиве.

Код выглядит следующим образом:

import React from 'react';
import { from } from 'rxjs';
import { map } from 'rxjs/operators';

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            fromArray: [1, 2, 3, 4, 5]
        };
    }

    componentDidMount() {
        const observable$ = from(this.state.fromArray).pipe(
            map(value => ({
                observable: value + 1
            }))
        );

        this._subscription = observable$.subscribe(
            result => this.setState({...result})
        )
    }

    componentWillUnmount() {
        this._subscription.unsubscribe();
    }

    render() {
        const { fromArray } = this.state;

        return (
            <ul>
                {
                    fromArray.map((item, index) => <li key={index}>{item}</li>)
                }
            </ul>
        )
    }
}

export default App;

Но у меня есть только начальный массив в списке.

Как заставить это работать?

1 Ответ

0 голосов
/ 30 апреля 2019

Здесь - это демо.Здесь есть 2 проблемы:

  • в функции map вы получаете обновленный элемент массива (2, 3, 4, 5, 6).Но вам нужно иметь сам новый массив, который будет установлен в состояние.Вот почему я использовал reduce.
  • , вам нужно указать, какую часть состояния вы устанавливаете.Не так: result => this.setState({...result}), а вот так: newFromArray => this.setState({ fromArray: newFromArray })

import React from "react";
import ReactDOM from "react-dom";

import { from } from "rxjs";
import { reduce } from "rxjs/operators";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      fromArray: [1, 2, 3, 4, 5]
    };
  }

  componentDidMount() {
    const observable$ = from(this.state.fromArray).pipe(
      reduce((acc, value) => [...acc, value + 1], [])
    );

    this._subscription = observable$.subscribe(newFromArray => {
      return this.setState({ fromArray: newFromArray });
    });
  }

  componentWillUnmount() {
    this._subscription.unsubscribe();
  }

  render() {
    const { fromArray } = this.state;

    return (
      <ul>
        {fromArray.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...