【发布时间】:2022-01-18 07:44:35
【问题描述】:
为什么 Step 组件在其 props (aStep) 更改时不会重新渲染?
//Game.svelte
import Step from './Step.svelte';
var states = [
{ name: "Red", next: 1, buttonText: "Goto2"},
{ name: "Yellow", next: 2, buttonText: "Goto3" },
{ name: "Green", next: 3, buttonText: "Goto4"},
{ name: "Blue", next: 0, buttonText: "Goto1"},
];
let curState = states[0]
var stepNumber = 1;
var theStep = undefined;
function nextStep() {
makeStep(curState, stepNumber);
stepNumber++;
curState=states[curState.next];
console.log(theStep)
}
function makeStep(state, stepNumber) {
theStep = {
title: "Step:" + stepNumber + " " +state.name,
buttonText: state.buttonText,
buttonAction: nextStep
}
}
</script>
<input id="startBtn" name="Submit" type="submit" value="Start" on:click={nextStep}/>
{#if theStep}
<Step aStep = {theStep}/>
{/if}
Step 组件:
<script>
export let aStep;
let {title, buttonText, buttonAction} = aStep
</script>
<div>
<p class = "title">{title}</p>
<div class ="stepBody">
<button on:click={buttonAction}>{buttonText}</button>
</div>
</div>
我可以通过console.log 看到theStep 会随着每一次按下按钮而改变,但Step 组件保持不变。
有一个 Svelte REPL here
【问题讨论】:
-
在 Step 组件中让 let 反应: $: {title, buttonText, buttonAction} = aStep;通过将 let 替换为 $: ...
-
@voscausa 我试过了,这让我在尝试使用和不使用 let/var/const 变体的 REPL 中出现错误
-
您不需要 let / var 或 const。 $: {title, buttonText, buttonAction} = aStep;会做
-
@voscausa 也试过了
-
尝试将所有内容都用括号括起来
$: ({title, buttonText, buttonAction} = aStep)