我是第一次接触flowtype,想请你帮我输入这个reducer。
// @flow
type State = {
[id: string]: boolean
};
type Action = { type: 'SET_ID', id: number, someValue: string };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'SET_ID':
const { id, someValue } = action;
return { [id]: someValue };
default:
(action: empty);
return state;
}
}我传递的操作id是一个数字,someValue是一个字符串,但是state id应该是string,someValue应该是boolean。流产生0个错误。有什么想法吗?
谢谢!
发布于 2017-11-17 00:18:50
我使用flow已经有一段时间了,还不是一个专业的人,但我想我也许能帮上忙。下面我要做的是,当ID是一个变量时,我不认为它需要被分配一个键--它只是一个字符串。它只分配了一个变量,因为你将它传递给一个函数并使用它--所以它所需要的只是一个字符串。这样,如果您向它传递一个数字,它现在应该抛出一个错误,这样您就可以决定是先将数字转换为字符串,还是先将初始项更改为数字,而不是状态类型中的字符串。
那么someValue就是键(字符串)的值,它也应该是一个字符串,而不是一个布尔值。
type State = {
[string]: string
};
type Action = { type: 'SET_ID', id: number, someValue: string };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'SET_ID':
const { id, someValue } = action;
return { [id.toString()]: someValue };
default:
(action: empty);
return state;
}
}从reducer返回的数据的一个示例可能是:
{'1231413413324': 'my new value from the reducer'}https://stackoverflow.com/questions/47333989
复制相似问题