这段代码到底发生了什么?它来自react-dnd docs。观察者是空的而不是函数,你怎么能让观察者o(甚至不知道' o代表什么)然后调用函数观察者(knightPosition)。
let knightPosition = [0, 0];
let observer = null;
function emitChange() {
observer(knightPosition);
}
export function observe(o) {
observer = o;
emitChange();
}
export function moveKnight(toX, toY) {
knightPosition = [toX, toY];
emitChange();
}
observe(knightPosition => {
render(
<Board knightPosition={knightPosition} />,
document.getElementById("root")
);
});
答案 0 :(得分:1)
React-DND在这里尝试实现的是类似Redux的流程,其中可以从组件内部更改和访问全局状态。
knightPosition
是全局保存在商店中的变量,必须进行更改。当变量发生变化时,我们必须触发一个可以更新React DOM的变更(emitChange
函数)。您可以查看带有注释的示例以获得更多解释。
let knightPosition = 0;
let observer = null;
function Board(props) {
return (
<div>
<p>{props.knightPosition}</p>
<button onClick={(e)=>moveKnight(10)}>Change</button>
</div>
);
}
function moveKnight(value) { //Changes the knightPosition value
knightPosition = value;
emitChange();
}
function emitChange() {
observer(knightPosition); // Calls the function reference it received with current knightPosition value
}
function observe(o) { //Sets the function reference it receives to observer variable.
observer = o;
emitChange();
}
function renderFunction(knightPosition) { //Just renders to DOM
ReactDOM.render(
<Board knightPosition={knightPosition} />,
document.getElementById("root")
);
}
observe(renderFunction); //Passing a reference of renderFunction to observe
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
为了简化,我已将knightPostion
变量从数组更改为变量。