Компонент не обновляется после отправки действия - реагировать на редукцию - PullRequest
0 голосов
/ 25 мая 2019

Я использую реактивную нативную систему, и у меня возникла проблема, когда мое действие отправляется, а редуктор изменяет состояние, однако мой компонент не выполняет повторную визуализацию. Мой редуктор использует оператор распространения для создания нового объекта. Похоже, что mapStateToProps больше не вызывается после обновления магазина. Я не уверен, что мне не хватает.

Создание провинции

class App extends React.Component {
  render() {
    return (
      <Provider store={createStore(rootReducer, middleware)}>
        <View style={styles.container}>
          <DeckListScreen />
        </View>
      </Provider>
    );
  }
}

Подключение компонента к провайдеру

class DeckListScreen extends React.Component {
  componentDidMount() {
    this.props.dispatch(handleInitialData())
  }

  render() {
    return(
      <View>
        <Text>{JSON.stringify(this.props.decks, null, 2)}</Text>
      </View
    )
  }
}
function mapStateToProps({decks}) {
  console.log('mapStateToProps - decks:', decks)
  return {
    decks: decks,
    loading: Object.keys(decks).length === 0 ? true : false
  }
}

export default connect(mapStateToProps)(DeckListScreen)

Редуктор, который возвращает новый объект

export default function decks(state = {}, action) {
  switch(action.type) {
    case GET_DECKS:
      const { decks } = action
      return {
          ...state,
          ...decks
      }
    default:
      return state
  }
}

Вот вывод консоли

Running application on iPhone.
mapStateToProps - decks: Object {}
mapStateToProps - decks: Object {}

ACTION TYPE:
GET_DECKS

OLD STATE:
Object {
  "decks": Object {},
}

ACTION:
Object {
  "decks": Object {
    "JavaScript": Object {
      "questions": Array [
        Object {
          "answer": "The combination of a function and the lexical environment within which that function was declared.",
          "question": "What is a closure?",
        },
      ],
      "title": "JavaScript",
    },
    "React": Object {
      "questions": Array [
        Object {
          "answer": "A library for managing user interfaces",
          "question": "What is React?",
        },
        Object {
          "answer": "The componentDidMount lifecycle event",
          "question": "Where do you make Ajax requests in React?",
        },
      ],
      "title": "React",
    },
  },
  "type": "GET_DECKS",
}

NEW STATE:  
Object {
  "decks": Object {
    "JavaScript": Object {
      "questions": Array [
        Object {
          "answer": "The combination of a function and the lexical environment within which that function was declared.",
          "question": "What is a closure?",
        },
      ],
      "title": "JavaScript",
    },
    "React": Object {
      "questions": Array [
        Object {
          "answer": "A library for managing user interfaces",
          "question": "What is React?",
        },
        Object {
          "answer": "The componentDidMount lifecycle event",
          "question": "Where do you make Ajax requests in React?",
        },
      ],
      "title": "React",
    },
  },
}

1 Ответ

1 голос
/ 27 мая 2019

createStore(rootReducer, middleware) необходимо ввести в отдельную переменную выше App.js. Каждый раз, когда App компонент выполняет рендеринг, создается новое хранилище, которое восстанавливает ваше состояние редуктора.

...