如何解构对象以从方法中检索 return 值?
How to destructure an object to retrieve the return value from a method?
我正在处理不可变性和 redux,我面临一个不严重的问题,但如果有解决方案,那就太好了。答案可能很愚蠢,但由于我是 ES 的新手,我在想我们如何才能实现它。
下面是我的减速器:
import Immutable from 'immutable';
import { TODOYO } from '../constants/action-types';
const initialState = Immutable.Map({
message: null,
});
export default function todos(state = initialState, action) {
switch (action.type) {
case TODOYO:
return state.set('message', action.payload);
default:
return state;
}
}
下面是我在组件中的 mapStateToProps 函数:
function mapStateToProps(state) {
const message = state.todos.get('message');
return {
message,
};
}
如何解构 state
以检索消息?
我在想这样的事情:
const {
todos: {
message: get('message')
}
} = state;
这是错误的。有没有办法找回消息?
如果您没有 message
作为您所在州的键之一,您可以使用 default parameters 语法来实现。如果消息在您的状态中确实以 属性 形式存在,则默认值将被覆盖。所以谨慎使用。
function mapStateToProps({ todos, message = todos.get('message') }) {
return {
message,
};
}
你也可以将mapStateToProps
缩短为箭头函数:
const mapStateToProps = ({ todos, message = todos.get('message') }) => ({
message
});
那是不可能的。只能解构arrays/objects,不能执行解构中的函数
The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
我正在处理不可变性和 redux,我面临一个不严重的问题,但如果有解决方案,那就太好了。答案可能很愚蠢,但由于我是 ES 的新手,我在想我们如何才能实现它。
下面是我的减速器:
import Immutable from 'immutable';
import { TODOYO } from '../constants/action-types';
const initialState = Immutable.Map({
message: null,
});
export default function todos(state = initialState, action) {
switch (action.type) {
case TODOYO:
return state.set('message', action.payload);
default:
return state;
}
}
下面是我在组件中的 mapStateToProps 函数:
function mapStateToProps(state) {
const message = state.todos.get('message');
return {
message,
};
}
如何解构 state
以检索消息?
我在想这样的事情:
const {
todos: {
message: get('message')
}
} = state;
这是错误的。有没有办法找回消息?
如果您没有 message
作为您所在州的键之一,您可以使用 default parameters 语法来实现。如果消息在您的状态中确实以 属性 形式存在,则默认值将被覆盖。所以谨慎使用。
function mapStateToProps({ todos, message = todos.get('message') }) {
return {
message,
};
}
你也可以将mapStateToProps
缩短为箭头函数:
const mapStateToProps = ({ todos, message = todos.get('message') }) => ({
message
});
那是不可能的。只能解构arrays/objects,不能执行解构中的函数
The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment