2017-10-17 81 views
1

您好我有我整合了Redux的一個組成部分我的反應的應用程序。我打開第二和第三部分。我不想把我在第一部分獲得的數據傳給道具中的第二和第三。如何共享終極版存儲在多個組件

我要做到這一點使用終極版店。有沒有辦法做到這一點?

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

第三component.js

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

在多個組件中使用redux商店的方式是什麼?

+0

有一大堆'react-redux'教程。 – lilezek

+0

[這不是一個好的做法](https://stackoverflow.com/questions/36638314/redux-with-react-right-way-to-share-the-store-with-components) –

+0

你正在使用一個可怕的很多你的組件中的'state'。使用Redux和'mapStateToProps'的原因是在你的'render'中使用道具。 – mhatch

回答

9

不限組件包裹有connect

connect(mapStateToProps, actions)(AnyComponent); 

將有權訪問整個redux存儲。
隨着mapStateToProps可以從redux商店經由props通過只相關的數據塊到所連接的組件。

關於組件內部state,我的經驗法則是設置內部狀態只是爲了那就是相關的特定組件的數據。
例如,extendcollapse狀態下拉。

至於ajax請求,如果你已經使用redux我強烈建議使用行動與thunkssagas並通過redux流通過新獲取的數據:
動作/咚 - >減速 - >連接組件。

編輯
作爲隨訪到您的評論,
你並不需要傳遞要連接到提供每個組件,您只需通過一個根組件(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
作爲後續到其他評論:

在道具等等傳遞價值部件或使用上面所說的方法, IDK這是推薦?

避免連接組件時,你可以和道具向下傳遞給孩子,這樣做的主要原因是爲了防止redux依賴。
我更願意盡我所能保持我的組件「啞巴」,並讓它們只關心事物的外觀。
我確實有一些組件關心應該如何工作,這些組件主要處理邏輯並將數據傳遞給子組件,它們是我經常連接的組件。

當我注意到我的應用程序正在縮放,並且我的一些組件正在充當道具的代理(我甚至對此有一個詞!「Propxy」),那就是他們從父母那裏獲得道具並將其傳遞給他人如果不使用它們,我通常會在組件樹的中間注入一個連接組件,這樣我就可以讓樹流中的「propxy」組件更加輕鬆和纖薄。

+0

這裏寫什麼','''''''''''''''如何在這裏設置多個組件? –

+0

所以將價值傳遞給組件或使用上述方法,建議使用Idk? –

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廣告等反應的組分。

+0

'const SecondComponent =({score})=>

{score}
'不應該'this.props.score'在這裏像'const SecondComponent =({score})=>
{this.props.score}
' –

+0

@Williams不,它是無狀態的功能組件 - https://www.jstwister.com/post/react-stateless-functional-components-best-practices/ 只有在使用類組件時才應該使用this.props.score – 1ven