簡體   English   中英

我如何從另一個 React 組件訪問 redux 狀態?

[英]How do i access redux state from another react component?

我正在開發一個彩票統計應用程序,它從從輸入加載的 csv 中獲取數據,然后我想將此數據讀取到 redux 存儲,以便我可以在多個組件中使用它。

導入文件並通過 Header.js 讀取並使用操作后,我已成功將數據保存到 redux 存儲,但我不確定如何在其他組件(例如 Main.js)中訪問它。

我覺得我仍然對 react/redux 如何組合在一起感到困惑。 如果之前有人問過這個問題,我很抱歉,但我在網上查到的所有內容都無法開始工作。

// index.js

import React from "react";
import ReactDOM from "react-dom";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import reducers from "./reducers";

import App from "./components/App";

const store = createStore(reducers, applyMiddleware(thunk));

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.querySelector("#root")
);
// App.js

import React from "react";

import Header from "./Header";
import Main from "./Main";

const App = () => {
  return (
    <div>
      <Header />
      <Main />
      <div className="numbers-for-draw"></div>
    </div>
  );
};

export default App;
// Header.js

import React from "react";
import { CSVReader } from "react-papaparse";
import { fetchData } from "../actions";
import { connect } from "react-redux";

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.fileInput = React.createRef();
  }

  handleReadCSV = data => {
    this.props.fetchData(data);
    console.log(this.props.data);
  };

  handleOnError = (err, file, inputElem, reason) => {
    console.log(err);
  };

  handleImportOffer = () => {
    this.fileInput.current.click();
    console.log("Got to handleImportOffer");
  };

  render() {
    return (
      <header>
        <CSVReader
          onFileLoaded={this.handleReadCSV}
          inputRef={this.fileInput}
          style={{ display: "none" }}
          onError={this.handleOnError}
        />
        <button onClick={this.handleImportOffer}>Import</button>
      </header>
    );
  }
}

//Map what is in the redux store (e.g. state) to props
const mapStateToProps = state => ({
  data: state.data
});

export default connect(mapStateToProps, {
  fetchData: fetchData
})(Header);
// Main.js

import React from "react";

import { fetchData } from "../actions";
import { connect } from "react-redux";

const Main = () => {
  console.log("In main");
  console.log(this.props.data);  //Blows up here. 
  return <div>Main</div>;
};

//Map what is in the redux store (e.g. state) to props
const mapStateToProps = state => ({
  data: state.data
});

export default connect(mapStateToProps, {
  fetchData: fetchData
})(Main);
// actions/index.js

export const fetchData = data => dispatch => {
  console.log("Action");
  const lottoData = {
    stringNumbers: [
      "one",
      "two",
      "three",
      ...
    ],

    allResults: [],
    winningNumbers: [],
    winningNumbersAsStrings: []
  };

  const localData = data.data;
  localData.shift();

  localData.forEach(line => {
    const lineObject = {
      draw: line[0],
      drawDate: line[1],
      ballOne: line[2],
      ballTwo: line[3],
      ballThree: line[4],
      ballFour: line[5],
      ballFive: line[6],
      ballSix: line[7],
      bonusBall: line[8],
      bonusBall2: line[9],
      powerBall: line[10]
    };

    lottoData.allResults.push(lineObject);

    let nums = [];
    nums.push(parseInt(line[2]));
    nums.push(parseInt(line[3]));
    nums.push(parseInt(line[4]));
    nums.push(parseInt(line[5]));
    nums.push(parseInt(line[6]));
    nums.push(parseInt(line[7]));

    nums.sort((a, b) => {
      if (a < b) {
        return -1;
      } else if (a > b) {
        return 1;
      } else {
        return 0;
      }
    });

    lottoData.winningNumbers.push(nums);
    lottoData.winningNumbersAsStrings.push(nums.toString());
  });

  dispatch({ type: "FETCH_DATA", payload: lottoData });
};

// lottoReducer.js

export default (state = {}, action) => {
  switch (action.type) {
    case "FETCH_DATA":
      return action.payload;
    default:
      return state;
  }
};
// reducers/index.js

import { combineReducers } from "redux";
import lottoReducer from "./lottoReducer";

export default combineReducers({
  data: lottoReducer
});

我還沒有測試過你的代碼,但在我看來唯一的問題是你的Main.js

當您使用函數組件而不是類時,您不應該使用this來訪問您的道具。 以下應該按預期工作:

const Main = (props) => {
  console.log("In main");
  console.log(props.data);  
  return <div>Main</div>;
};

//Map what is in the redux store (e.g. state) to props
const mapStateToProps = state => ({
  data: state.data
});

export default connect(mapStateToProps, {
  fetchData: fetchData
})(Main);

在您的 main.js 中,您使用了功能組件,因此this.props在那里不起作用。 您必須將道具傳遞給您的組件和console.log(props.data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM