【发布时间】:2019-07-26 23:35:01
【问题描述】:
我正在尝试从 react reducer 中的 api 初始化我的应用程序数据。 api调用,reducer上调用dispatch,但是函数组件重新渲染的时候,依然是初始状态。
以下是相关代码:
Ui.js
import { useReducer } from 'react';
import api from './api';
const reducer = (state: Object, action: {type: string, data: Object}) => {
switch (action.type) {
case 'init':
return action.data;
}
};
class Ui {
constructor(schematicId) {
const initialState = {loadingStatus: 'Loading...'};
[this.state, this.dispatch] = useReducer(reducer, initialState);
this.schematicId = schematicId;
api.init(schematicId).then(data => {
this.dispatch({type: 'init', data: data});
});
}
}
export default Ui;
index.js
let alertStore;
let ui;
const App = props => {
alertStore = alertStore || new AlertStore();
ui = ui || new Ui(props.schematicId);
return (
<div className="container-fluid">
{alertStore.alerts.map((a, index) => (
<Alert dismissible key={index}
onClose={() => alerts.remove(index)}
variant={a.variant}>{a.msg}</Alert>
))}
<LoadingBoundary status={ui.state.loadingStatus}>
...
</LoadingBoundary>
</div>
);
};
我原来只是有
alertStore = new AlertStore();
ui = new Ui(schematicId);
但它导致网页冻结。我认为 Ui.js 文件中的某些内容在将其更改为之前导致了无限循环
alertStore = alertStore || new AlertStore();
ui = ui || new Ui(props.schematicId);
因为我之前在其他应用中使用过alertStore = new AlertStore(); 没有问题。
我在 index.js 和 Ui.js 中设置了断点。 index.js 在 Ui.js 中 switch 语句后重新渲染,但状态仍然是 {loadingStatus: 'Loading...'} 而不是 api 返回的状态。
【问题讨论】:
-
您能否像
Ui一样在您的开发控制台中使用类似useReducer can't be used in non-Function Component的警告进行确认? -
Ui 不是 React 组件。 React 没有抱怨,因为调用 useReducer 的类在 App 中被调用,这是一个函数组件。我会在星期一再次检查,但 AlertStore 类几乎与 Ui 相同,只是它没有 api 调用。当我让 AlertStore 在另一个应用程序中工作时发生的所有交互都来自 React 组件内部的调用。
标签: reactjs state react-hooks