我只是在制作一个简单的应用程序来学习与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')
);

所以,在状态的render方法中,我想列出存储区中的所有item.title个.

谢谢

推荐答案

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

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

Reactjs相关问答推荐

webpack 5中动态导入的路径

在Redux工具包查询中,是否可以将标记应用到API切片内的所有端点?

react 副作用循环

For循环中的元素在Reaction中丢失挂钩

TypeError:SearchProduct.get()获得了意外的关键字参数查询'

梅X折线图无响应

MUiv5和TSS-Reaction SSR问题:无法可靠地处理样式定义.CSSprops 中的ArrowFunctionExpression

Reaction上下文值无法传递给其他组件

状态更改时的rtk查询触发器

React useEffect 问题...异步函数内的变量正在获取延迟的更新值

在 React 中,如何在指向同一组件的路由中拥有未定义数量的多个动态路径段?

如何将 DocuSign 控制台界面嵌入到 React 应用中

如何在屏幕上使用相同的可重用

如何防止开发人员使用 ESLint 在 React 项目中使用特定的钩子?

我正在try 将一组加载程序函数发送到我的路由,它抛出一个错误 Handler is not a funtion in a reactJs application

我如何在所有组件中使用 Chakra UI toast?

我应该使用 useEffect 来为 React Native Reanimated 的 prop 值变化设置动画吗?

调用 Jest 和服务方法的问题

使用 React、Redux 和 Firebase 的无限循环

无法重用我的组件,它只显示 1 次