简体   繁体   English

为什么 redux 存储状态在 render() 中显示为“false”,即使默认状态为“true”?

[英]Why is the redux store state showing `false` within render(), even though the default state is `true`?

I have the following code.我有以下代码。 It is using an older version of React, but why does the redux store state, !!this.state.checked , show up as false within render() ... Despite the defaultState being true ?它使用的是旧版本的 React,但为什么 redux 存储状态!!this.state.checkedrender()显示为false ......尽管defaultStatetrue

index.js索引.js

import ReactDOM from 'react-dom';
import React from 'react';
import { createStore } from 'redux';



const defaultState = { checked: true };
const reducer = (state = defaultState, action) => {
  switch (action.type) {
    case 'TOGGLE':
      return { ...state, checked: !state.checked };
    default:
      return state;
  }
};
const store = createStore(reducer);



class App extends React.Component {

  constructor() {
    super();
    this.state = {};
  }

  // deprecated from react version 17
  // but this is using react version 15 only
  componentWillMount() {
    store.subscribe(() => this.setState(store.getState()));
  }

  render() {
    return (
      <div>
        why is this still false?
        {
          String(!!this.state.checked)
        }
      </div>
    );
  }
}



ReactDOM.render((
  <App />
), document.getElementById('root'));

index.html索引.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Doesn't Work!</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

package.json (partly) package.json(部分)

  ...

  "dependencies": {
    "history": "^4.3.0",
    "marked": "^0.3.6",
    "react": "^15.3.2",
    "react-dom": "^15.3.2",
    "react-redux": "^4.4.5",
    "react-router": "^2.8.1",
    "redux": "^3.6.0",
    "superagent": "^2.3.0",
    "superagent-promise": "^1.1.0"
  },

  ...

I've created a Codesandbox demonstrating the order of procedure and the current redux state.我创建了一个Codesandbox 来演示程序的顺序和当前的 redux 状态。

As you can see, the Redux state is actually up-to-date with the state you'd expect.如您所见,Redux 状态实际上与您期望的状态保持同步。 However, the component state is never being set initially.但是,最初从未设置组件状态。 This is because the callback you are passing to the subscribe function is never called on mount.这是因为您传递给subscribe 函数的回调永远不会在挂载时调用。

You can solve this problem by setting the initial state to the redux state in the constructor:您可以通过在构造函数中将初始状态设置为 redux 状态来解决此问题:

class App extends React.Component {

  constructor() {
    super();
    this.state = store.getState();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM