Material-UI开关状态未从数据库值更新

时间:2018-11-27 15:18:31

标签: javascript reactjs firebase material-ui react-redux-firebase

更新Firebase值时,Material-ui开关未更新。

我在此处仅发布了一部分代码,完整的演示可在CodeSandbox上找到。

该项目已连接到Firebase,并使用depenedncies:react-redux-firebase,redux-firestore等,您可以在演示中找到所有详细信息。

CodeSandobox Demo

import React, { Component } from "react";
import styled from "styled-components";
import { connect } from "react-redux";
import { firestoreConnect } from "react-redux-firebase";
import { compose } from "redux";
import Switch from "@material-ui/core/Switch";

import { toggleStatus } from "../actions/statusActions";

const Wrapper = styled.div`
  padding-top: 50px;
`;

const OnOff = styled.span`
  ${props => `color: ${props.color}`};
`;

class Header extends Component {
  hanldeToggleStats = () => {
    const { status } = this.props;
    const dbStatus = status && status[0].status;
    this.props.toggleStatus(dbStatus);
  };

  render() {
    const { status } = this.props;
    const dbStatus = status && status[0].status;
    console.log("dbStatus:", dbStatus);

    return (
      <Wrapper>
        <div>
          Change status, refresh the page, observe difference between labels and
          Switch
        </div>
        <OnOff color={dbStatus ? "#BDBDBD" : "#7AC943"}>Off</OnOff>
        <Switch
          checked={dbStatus}
          onChange={this.hanldeToggleStats}
          color="primary"
        />
        <OnOff color={dbStatus ? "#7AC943" : "#BDBDBD"}>On</OnOff>
      </Wrapper>
    );
  }
}

const mapStateToProps = state => {
  return {
    status: state.firestore.ordered.status //this returns true
  };
};

const mapDispatchToProps = dispatch => {
  return {
    toggleStatus: status => dispatch(toggleStatus(status))
  };
};

export default compose(
  connect(
    mapStateToProps,
    mapDispatchToProps
  ),
  firestoreConnect([
    { collection: "status", limit: 1, orderBy: ["createdAt", "desc"] }
  ])
)(Header);

1 个答案:

答案 0 :(得分:1)

const dbStatus = Boolean(status && status[0].status);

const dbStatus = status && status[0].status;可能导致dbStatus未被定义,因此该组件被视为不受控制。一旦定义,您应该得到警告。