秘银:vnode.attrs 和 vnode.state 的区别
Mithril: difference between vnode.attrs and vnode.state
在 Mithril 中创建新组件时,vnode.attrs.value
和 vnode.state.value
有什么区别?
如documentation所述:
州
An object that is persisted between redraws. It is provided by the
core engine when needed. In POJO component vnodes, the state inherits
prototypically from the component object/class. In class component
vnodes it is an instance of the class. In closure components it is the
object returned by the closure.
属性
A hashmap of DOM attributes, events, properties and lifecycle methods.
例如看一下这段代码。
class Hello {
constructor(height, width) {
this.txt = 'from state'
}
view (vnode) {
console.log(vnode.state)
return m("main", [
m("h1", {class: "title"}, "This come "+vnode.attrs.txt),
m("h1", {class: "title"}, "This come "+vnode.state.txt)
])
}
}
m.mount(root, {view: function () {return m(Hello, {txt: 'from attribute'})}})
输出将显示状态是从组件构造函数初始化的。属性是从 m() 传递的。
一般来说,当在上下文中使用它时,您可以使用 attrs 将数据传递给对象(例如,将 URL 传递给组件以供 ajax 使用)。取而代之的是使用 state 在重绘中保留组件的本地数据(即用于重置目的的字段初始状态)
在 Mithril 中创建新组件时,vnode.attrs.value
和 vnode.state.value
有什么区别?
如documentation所述:
州
An object that is persisted between redraws. It is provided by the core engine when needed. In POJO component vnodes, the state inherits prototypically from the component object/class. In class component vnodes it is an instance of the class. In closure components it is the object returned by the closure.
属性
A hashmap of DOM attributes, events, properties and lifecycle methods.
例如看一下这段代码。
class Hello {
constructor(height, width) {
this.txt = 'from state'
}
view (vnode) {
console.log(vnode.state)
return m("main", [
m("h1", {class: "title"}, "This come "+vnode.attrs.txt),
m("h1", {class: "title"}, "This come "+vnode.state.txt)
])
}
}
m.mount(root, {view: function () {return m(Hello, {txt: 'from attribute'})}})
输出将显示状态是从组件构造函数初始化的。属性是从 m() 传递的。
一般来说,当在上下文中使用它时,您可以使用 attrs 将数据传递给对象(例如,将 URL 传递给组件以供 ajax 使用)。取而代之的是使用 state 在重绘中保留组件的本地数据(即用于重置目的的字段初始状态)