如何在多个组件中共享redux store

时间:2017-10-17 18:58:41

标签: javascript reactjs react-native redux react-redux

您好我有一个组件,我在我的react应用程序中集成了redux。我打开第二个然后是第三个组件。我不希望将我在第一个组件中获得的数据传递给道具中的第二个然后第三个。

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

App.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);

index.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();

secondcomponent.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 个答案:

答案 0 :(得分:12)

connect包裹的任何组件:

connect(mapStateToProps, actions)(AnyComponent);

可以访问整个 redux商店 使用mapStateToProps,您可以通过reduxprops商店中的相关数据传递到连接的组件。

关于组件内部state,我的经验法则是仅针对与特定组件相关的数据设置内部状态。
例如,extendcollapse表示下拉列表。

对于ajax请求,如果您已使用redux,我强烈建议您使用thunkssagas的操作,并通过{{1}传递新获取的数据流量:
动作/ thunk - &gt;减速器 - &gt;连通组件。

修改
作为评论的后续内容,
您不需要传递要连接到提供程序的每个组件,只需传递一个根组件(redux在您的案例中),App的每个子项都可以连接到{{1如有必要:

App

以及其他组件:

redux

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

  

所以将道具中的值传递给组件或使用上述方法,   Idk哪个推荐?

尽可能避免连接组件并将道具传递给孩子,主要原因是为了防止依赖class SecondComponent extends Component { render() { return ( // print score which is in redux <div>this.props.score</div> ); } } export default connect(mapStateToProps)(SecondComponent);
我更喜欢保留我的组件&#34; dumb&#34;尽我所能,让他们只关注事物的外观 我确实有一些关于事情应该如何工作的组件,这些组件主要处理逻辑并将数据传递给子节点,它们是我经常连接的组件。

当我注意到我的应用程序正在缩放并且我的一些组件充当道具的代理(我甚至得到了一个词!&#34; Propxy&#34;),那就是他们从他们的父母获得道具并且在不使用它们的情况下将它们传递下来,我通常在组件树的中间注入一个连接组件,这样我就可以让#34; propxy&#34;树木流下的组件更加轻盈和纤细。

答案 1 :(得分:1)

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

不要试图通过上下文访问商店,只需使用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)

您可以对任何反应组件使用连接,例如ThirdComponent广告等。