繁体   English   中英

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

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

我有以下代码。 它使用的是旧版本的 React,但为什么 redux 存储状态!!this.state.checkedrender()显示为false ......尽管defaultStatetrue

索引.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'));

索引.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(部分)

  ...

  "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"
  },

  ...

我创建了一个Codesandbox 来演示程序的顺序和当前的 redux 状态。

如您所见,Redux 状态实际上与您期望的状态保持同步。 但是,最初从未设置组件状态。 这是因为您传递给subscribe 函数的回调永远不会在挂载时调用。

您可以通过在构造函数中将初始状态设置为 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