如何在React Redux中访问存储状态?

Par*_*ism 65 javascript asynchronous reactjs redux react-redux

我只是制作一个简单的应用程序来学习与redux的异步.我已经完成了所有工作,现在我只想在网页上显示实际状态.现在,我如何在render方法中实际访问商店的状态?

这是我的代码(一切都在一页,因为我只是在学习):

const initialState = {
        fetching: false,
        fetched: false,
        items: [],
        error: null
    }

const reducer = (state=initialState, action) => {
    switch (action.type) {
        case "REQUEST_PENDING": {
            return {...state, fetching: true};
        }
        case "REQUEST_FULFILLED": {
            return {
                ...state,
                fetching: false,
                fetched: true,
                items: action.payload
            }
        }
        case "REQUEST_REJECTED": {
            return {...state, fetching: false, error: action.payload}   
        }
        default: 
            return state;
    }
};

const middleware = applyMiddleware(promise(), thunk, logger());
const store = createStore(reducer, middleware);

store.dispatch({
    type: "REQUEST",
    payload: fetch('http://localhost:8000/list').then((res)=>res.json())
});

store.dispatch({
    type: "REQUEST",
    payload: fetch('http://localhost:8000/list').then((res)=>res.json())
});

render(
    <Provider store={store}>
        <div>
            { this.props.items.map((item) => <p> {item.title} </p> )}
        </div>
    </Provider>,
    document.getElementById('app')
);
Run Code Online (Sandbox Code Playgroud)

所以,在状态的render方法中我想列出所有item.title来自商店的东西.

谢谢

1ve*_*ven 45

您应该创建单独的组件,它将监听状态更改并更新每个状态更改:

class Items extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: [],
    };

    store.subscribe(() => {
      // When state will be updated(in our case, when items will be fetched), 
      // we will update local component state and force component to rerender 
      // with new data.

      this.setState({
        items: store.getState().items;
      });
    });
  }

  render() {
    return (
      <div>
        {this.state.items.map((item) => <p> {item.title} </p> )}
      </div>
    );
  }
};

render(<Items />, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)

  • @ 1ven如何在这里定义`store`变量? (55认同)
  • @BangDao为了清楚起见,你应该包含`store` import. (20认同)
  • ReferenceError无法找到变量:store (4认同)
  • `import store from'../ reducers/store';`.和`store.js`将包含`const createStoreWithMiddleware = applyMiddleware(thunkMiddleware,promise)(createStore); export default createStoreWithMiddleware(reducers);` (3认同)
  • @BangDao我们可以假设,我们是从外部文件导入它.`store`变量 - 它是redux store实例. (2认同)

Zak*_*sri 39

connect从中导入react-redux并使用它将组件与状态连接起来connect(mapStates,mapDispatch)(component)

import React from "react";
import { connect } from "react-redux";


const MyComponent = (props) => {
    return (
      <div>
        <h1>{props.title}</h1>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

最后,您需要将状态映射到道具以使用它们来访问它们 this.props

const mapStateToProps = state => {
  return {
    title: state.title
  };
};
export default connect(mapStateToProps)(MyComponent);
Run Code Online (Sandbox Code Playgroud)

只有您映射的状态才能通过 props

看看这个答案:https://stackoverflow.com/a/36214059/4040563

如需进一步阅读:https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132

  • 注意:这样,如果不调用操作(在`mapDispatchToProps` 中定义),就无法访​​问道具。如果您试图在不调度另一个获取周期的情况下获取商店中已有的内容,那么您必须在“商店”上使用“订阅”或“getState”。 (4认同)

Ilm*_*ula 25

所有的答案都来自前钩子时代。您应该使用 useSelector-hook 从 redux 获取状态。

在你的 redux-reducer 文件中或者你可以轻松导入它的地方:

import { useSelector } from 'react-redux'

export function useEmployees() {
  return useSelector((state) => state.employees)
}
Run Code Online (Sandbox Code Playgroud)

在您的应用程序代码中:

const { employees } = useEmployees()
Run Code Online (Sandbox Code Playgroud)

有关 redux-hooks 的更多信息:https://react-redux.js.org/api/hooks来实现此目标。

  • 为什么我们需要另一个钩子来替代 useSelector()?```const 员工 = useSelector( state =&gt; state.employees)``` (2认同)
  • @Yogi,您完全可以使用它而无需额外的挂钩。我个人更喜欢仅将 Redux 特定的 useSelector 保留在 Redux 文件夹下。第二个原因是我发现 useEmployees 更具表现力 (2认同)

sem*_*ser 12

您需要使用Store.getState()获取商店的当前状态.

有关getState()观看简短视频的更多信息.


Bra*_*don 6

您不仅仅想做更多的事情getState。您想对商店中的更改做出反应。

如果您不使用react-redux,则可以执行以下操作:

function rerender() {
    const state = store.getState();
    render(
        <div>
            { state.items.map((item) => <p> {item.title} </p> )}
        </div>,
        document.getElementById('app')
    );
}

// subscribe to store
store.subscribe(rerender);

// do initial render
rerender();

// dispatch more actions and view will update
Run Code Online (Sandbox Code Playgroud)

但是更好的方法是使用react-redux。在这种情况下,您可以像前面提到的那样使用提供程序,然后使用connect将组件连接到商店。

  • 该操作员特别要求使用React-Redux。为什么要提供请求以外的解决方案? (6认同)

Mow*_*zer 5

如果您想做一些高性能的调试,您可以订阅状态的每个变化并暂停应用程序以查看详细情况,如下所示。

商店.js
store.subscribe( () => {
  console.log('state\n', store.getState());
  debugger;
});
Run Code Online (Sandbox Code Playgroud)

将其放在文件中您所做的位置createStore

state要将对象从控制台复制到剪贴板,请按照下列步骤操作:

  1. 右键单击 Chrome 控制台中的对象,然后从上下文菜单中选择“存储为全局变量”。它将返回类似 temp1 的内容作为变量名。

  2. Chrome 也有一个copy()方法,因此copy(temp1)在控制台中应该将该对象复制到剪贴板。

/sf/answers/1759840351/

https://scottwhittaker.net/chrome-devtools/2016/02/29/chrome-devtools-copy-object.html

您可以在 json 查看器中查看该对象,如下所示:http ://jsonviewer.stack.hu/

您可以在这里比较两个 json 对象: http: //www.jsondiff.com/