【发布时间】:2020-10-23 12:09:23
【问题描述】:
我有一个模式,其中包含一个触发 HTTP 请求的按钮,此时显示的 html 将根据来自服务器的成功/错误响应而改变,其中响应会更改在 @987654322 中处理的状态道具@函数。
我现在遇到的问题是,当我关闭它时,我想将模式重置为其初始状态预请求。 我以前通过使用本地组件状态来完成此操作,但后来更新了使用上面显示的请求映射状态道具的功能。
我很好奇是否可以在不触发随机 URI 调度的情况下重置状态?
Component.jsx
const mapStatesToProps = ({myState}) => ({
response: myState.response,
success: !!(myState.success),
fail: !!(myState.fail)
});
const mapDispatchToProps = dispatch => ({
doReq: () => {
dispatch(doMyRequest());
}
});
class MyComponent extends Component {
toggleModal = () => // modal toggle code
render() {
const {response, success, fail} = this.props;
<div className="myModal">
// Modal stuff here
{!success && !fail && (
<button onClick="() => toggleModal()">Close modal</button>
)}
{success && !fail && (
<h1>Some success message</h1>
)}
{!success && fail && (
<h1>Some fail message</h1>
)}
</div>
}
}
req-actions.js
export const MY_REQUEST;
export const MY_REQUEST_SUCCESS;
export const MY_REQUEST_ERROR;
export const doMyRequest = () => ({
type: MY_REQUEST,
agent: agent.req.doRequest
})
req-reducer.js
import { deepEqual, deepClone } from '../McUtils';
import {
MY_REQUEST,
MY_REQUEST_ERROR,
MY_REQUEST_SUCCESS
} from "../actions/req-actions";
export default (state = {}, action) => {
let newState = deepClone(state);
switch (action.type) {
case MY_REQUEST:
console.log('SENDING REQUEST');
newState.response = null;
newState.success = false;
newState.fail = false;
break;
case MY_REQUEST_SUCCESS:
console.log('SUCCESS');
newState.response = action.payload;
newState.success = true;
newState.fail = false;
break;
case MY_REQUEST_ERROR:
console.log('FAIL');
newState.response = action.payload;
newState.success = false;
newState.fail = true;
break;
default:
return state;
}
return newState;
}
【问题讨论】:
-
不清楚您要的是什么。 modal 里面是什么,一个表单?
-
与其在关闭模态时重置状态而不发送请求,不如将 draft 保持在模态的本地状态并仅将其保存到 redux传输成功后存储。只是因为应用程序使用了 redux,所以没有理由将每个中间状态存储在商店中。如果模态框包含一个表单,那么除非提交,否则表单状态可能应该是该表单的本地状态。 modal 应该是一个自己的组件,在打开时会从 store 中以初始状态安装。
-
非常同意@trixn。 Redux 用于应用程序状态,而不是临时状态。这里是defined by flutter,但在反应中它是 100% 完全相同的东西。我无法告诉你在开发人员决定将所有内容放入redux而不是在适用时使用本地状态的应用程序上工作是多么令人抓狂。
标签: javascript reactjs redux react-redux