0

更新 firebase 值时,Material-ui 开关不会更新。

我在这里只发布了一部分代码,完整的 Demo 可以在 CodeSandbox 上找到。

该项目连接到firebase并使用依赖项为:react-redux-firebase,redux-firestore等,您可以在Demo中找到所有详细信息。

CodeSandobox 演示

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);
4

1 回答 1

1

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

const dbStatus = status && status[0].status;可能导致dbStatus未定义组件被认为是不受控制的。一旦它被定义,你应该得到一个警告。

于 2018-11-27T17:21:35.723 回答