当前位置: 首页 > 知识库问答 >
问题:

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

陆弘光
2023-03-14

我只是做了一个简单的应用程序学习异步与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')
);

谢谢

共有1个答案

岳正浩
2023-03-14

您应该创建单独的组件,该组件将监听状态更改并在每次状态更改时进行更新:

import store from '../reducers/store';

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'));
 类似资料:
  • 问题内容: 我只是做一个简单的应用程序来学习与redux异步。我已经使所有工作正常进行,现在我只想在网页上显示实际状态。现在,我实际上如何在render方法中访问商店的状态? 这是我的代码(所有内容都在一页中,因为我只是在学习): 因此,在状态的render方法中,我想列出商店中的所有内容。 谢谢 问题答案: 您应该创建单独的组件,该组件将侦听状态更改并在每次状态更改时进行更新:

  • 问题内容: 在进行Ajax调用的redux-form 函数中,Ajax中需要Redux状态的某些属性(例如,用户ID)。 这将是很容易的,如果我想定义形式的成分,只要调用:在任何我需要传递,并从阅读中我的。 但是,像一个出色的React-Redux开发人员一样,我编写了 单独的视图组件和容器 ,因此视图组件可以很简单,几乎没有行为。因此,我想 在我的container中定义handleSubmit

  • 对于vue-axios auth by api_token,我使用助手文件api.js。

  • 我试图在我的云功能中访问Firebase云存储,但我一直在云功能日志中出现以下错误: 下面是我的代码: const admin=需要('Firebase-admin'); const函数=需要('Firebase-函数'); 下面是我的包中的依赖项。json: PS:我在星火计划上

  • 问题内容: 我有一个化简器,为了计算新状态,我需要操作中的数据以及该化简器未管理的部分状态数据。具体来说,在下面将显示的减速器中,我需要访问该字段。 initialState.js: FormsReducer.js: index.js(根减速器): 如何访问此字段? 问题答案: 我将为此使用thunk,这是一个示例: 基本上,您会获得操作所需的所有数据,然后可以将该数据发送到减速器。

  • 我已经写了一个代码来录制音频并保存到下面的文件位置。 在Logcat中,它为我提供了一个文件位置 我无法在SD卡上找到此文件位置。如何访问该位置?