如何在多个组件中共享 redux 存储

IT技术 javascript reactjs react-native redux react-redux
2021-04-28 16:21:19

嗨,我有一个组件,我将 redux 集成到我的 React 应用程序中。我正在打开第二个然后第三个组件。我不希望将我在第一个组件中获得的数据传递给props中的第二个然后第三个。

我想使用 redux store 来做到这一点。有没有办法做到这一点?

应用程序.js

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import RoundedButton from "./RoundedButton";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as actions from "./actions/index";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      score: 0,
      status: "",
      userSelected: "",
      computerSelected: "",
      visibility: [true, true, true],
      buttonVisibility: false
    };
    this.clickitem = this.clickitem.bind(this);
    this.handlePlayAgain = this.handlePlayAgain.bind(this);
  }

  handlePlayAgain() {
    this.setState({
      buttonVisibility: false,
      visibility: [true, true, true]
    });
  }

  clickitem(user) {
    var url = "http://localhost:4000/generate-random";
    this.setState({ userSelected: user });

    fetch(url)
      .then(response => {
        if (response.status >= 400) {
          throw new Error("Bad response from server");
        }
        return response.json();
      })
      .then(data => {
        var computer = data.item;
        this.setState({ computerSelected: computer });
        if (
          (user === "Rock" && computer === "Scissors") ||
          (user === "Paper" && computer === "Rock") ||
          (user === "Scissors" && computer === "Paper")
        ) {
          this.props.increment();
        } else if (user === computer) {
          this.props.doNothing();
        } else {
          this.props.decrement();
        }

        console.log(user + " " + computer);
        console.log("------------------------------------");

        App.contextTypes = { store: React.PropTypes.object };
        let store = this.context.store;
        console.log(store);

        arrayvar = [];

        var arrayvar = [];
        if (user === "Rock" && computer === "Rock") {
          arrayvar = [true, false, false];
        } else if (user === "Paper" && computer === "Paper") {
          arrayvar = [false, true, false];
        } else if (user === "Scissors" && computer === "Scissors") {
          arrayvar = [false, false, true];
        } else if (
          (user === "Rock" && computer === "Paper") ||
          (user === "Paper" && computer === "Rock")
        ) {
          arrayvar = [true, true, false];
        } else if (
          (user === "Rock" && computer === "Scissors") ||
          (user === "Scissors" || computer === "Rock")
        ) {
          arrayvar = [true, false, true];
        } else if (
          (user === "Paper" && computer === "Scissors") ||
          (user === "Scissors" || computer === "Paper")
        ) {
          arrayvar = [false, true, true];
        }
        this.setState({ visibility: arrayvar });
        this.setState({
          buttonVisibility: true
        });
      });
  }

  render() {
    return (
      <div className="CenterDiv">
        <div className="AppTitle">
          <b>Score: {this.props.score}</b>
          <div>
            {this.state.visibility[0]
              ? <RoundedButton
                  text="Rock"
                  clickitem={this.clickitem}
                  label={
                    this.state.userSelected === "Rock" &&
                      this.state.computerSelected === "Rock"
                      ? "User & Computer Selected"
                      : this.state.userSelected === "Rock"
                        ? "User Selected"
                        : this.state.computerSelected === "Rock"
                          ? "Computer Selected"
                          : ""
                  }
                />
              : null}
            {this.state.visibility[1]
              ? <RoundedButton
                  text="Paper"
                  clickitem={this.clickitem}
                  label={
                    this.state.userSelected === "Paper" &&
                      this.state.computerSelected === "Paper"
                      ? "User & Computer Selected"
                      : this.state.userSelected == "Paper"
                        ? "User Selected"
                        : this.state.computerSelected === "Paper"
                          ? "Computer Selected"
                          : ""
                  }
                />
              : null}
            {this.state.visibility[2]
              ? <RoundedButton
                  text="Scissors"
                  clickitem={this.clickitem}
                  label={
                    this.state.userSelected === "Scissors" &&
                      this.state.computerSelected === "Scissors"
                      ? "User & Computer Selected"
                      : this.state.userSelected === "Scissors"
                        ? "User Selected"
                        : this.state.computerSelected === "Scissors"
                          ? "Computer Selected"
                          : ""
                  }
                />
              : null}
          </div>

          <div className="Status">{this.props.status}</div>

          {this.state.buttonVisibility
            ? <button onClick={this.handlePlayAgain} style={{ margin: 30 }}>
                Play Again
              </button>
            : null}

        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return { score: state.score, status: state.status };
}

export default connect(mapStateToProps, actions)(App);

索引.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";
import "./index.css";

import { Provider } from "react-redux";
import { createStore } from "redux";
import scoreReducer from "./reducers";

let store = createStore(scoreReducer);

ReactDOM.render(
  <Provider store={store}><App /></Provider>,
  document.getElementById("root")
);
registerServiceWorker();

第二个组件.js

export default class SecondComponent extends Component {
  render() {
    return (
       // print score which is in redux
    );
  }
}

第三个组件.js

export default class ThirdComponent extends Component {
  render() {
    return (
       // print score which is in redux
    );
  }
}

在多个组件中访问 redux 存储的方法是什么?

2个回答

任何用 包裹的组件connect

connect(mapStateToProps, actions)(AnyComponent);

将可以访问整个 redux商店。
有了它,mapStateToProps您就可以redux通过props.

关于 component internal state,我的经验法则是只为与特定组件相关的数据设置内部状态。
例如,extendcollapse状态下拉菜单。

至于ajax请求,如果您已经在使用,redux我强烈建议您使用带有thunks或的操作,sagas并通过redux传递新获取的数据
Action/thunk -> Reducers -> connected components。

编辑
作为您评论的后续,
您不需要将要连接到提供程序的每个组件都传递给提供者,您只需传递一个根组件(App在您的情况下),并且每个子组件都App可以redux在必要时连接

class SecondComponent extends Component {
  render() {
    return (
       // print score which is in redux
       <div>this.props.score</div> 
    );
  }
} 

export default connect(mapStateToProps)(SecondComponent);

以及其他组件:

class ThirdComponent extends Component {
  render() {
    return (
       // print score which is in redux
       <div>this.props.score</div> 
    );
  }
} 

export default connect(mapStateToProps)(ThirdComponent);

编辑 #2
作为您其他评论的后续:

因此,将props中的值传递给组件或使用上述方法,推荐使用 Idk 吗?

尽可能避免连接组件并将 props 传递给孩子,这样做的主要原因是为了防止对redux.
我更喜欢尽可能保持我的组件“愚蠢”,让他们只关心事情应该是什么样子。
我确实有一些关注事物应该如何工作的组件,这些组件主要处理逻辑并将数据传递给孩子,它们是我经常连接的组件。

当我注意到我的应用程序正在扩展并且我的一些组件充当 props 的代理时(我什至有一个词!“Propxy”),也就是说它们从它们的父级获取 props 并在不使用它们的情况下传递它们,我通常在组件树的中间注入一个连接的组件,这样我就可以让树流中的“propxy”组件更轻更薄。

redux在 React 应用程序中使用的通用方法是将它与react-redux一起使用该库提供了connect功能,有助于以更干净的方式访问react组件中的存储。

不要尝试通过上下文访问存储,只需使用connect函数:

import { connect } from 'react-redux';

const SecondComponent = ({ score }) => <div>{score}</div>

// with help of `connect`, you are providing `score` prop to `SomeComponent`
// next, you can render that connected component anywhere in your app
export default connect(
  (state) => ({
    score: state.score
  })
)(SecondComponent)

您可以将 connect 用于您的任何react组件,例如ThirdComponent广告等。