React - 当按钮增加并在另一个页面中渲染结果时增加计数器的最佳方法?

问题描述 投票:1回答:1

我是React和Javascript世界的新手,并试图通过制作Magic 8 Ball应用程序来投入一些开发。

我有两页设置:

  1. 神奇的8球游戏页面
  2. 统计页面显示有关魔术8球问题的信息

游戏页面功能有效(使用下面的server.js文件中的代码片段),但我现在想要将游戏页面中的信息传递给统计页面上的问题总数。

我的基本想法是:

  • 单击该按钮时,我想将计数器增加1
  • 将此计数器值存储在本地存储中并返回统计页面(只是想立即打印)

我遇到了一些不同的方法,但只需要一些关于最佳方法的指导。

到目前为止,我在实现这个目的之前已经汇总了几个片段:

index.js文件

<form className="question-input" method="POST" action="/">
  <input type="text" ref="inputquestion" placeholder="Ask your question..."style={{ width: "300px", fontSize:18 }}/>
  <button id="submitquestion" style={{ width: "100px", fontSize:17 }}>Shake Me!</button>
</form>

server.js文件

  server.post('/', (req,res) => {
    console.log("Received request.")
    const answers = [
      "It is certain.",
      "It is decidedly so.",
      "Without a doubt.",
      "Yes - definitely.",
      "You may rely on it.",
      "As I see it, yes.",
      "Most likely.",
      "Outlook good.",
      "Yes.",
      "Signs point to yes.",
      "Reply hazy, try again.",
      "Ask again later.",
      "Better not tell you now.",
      "Cannot predict now.",
      "Concentrate and ask again.",
      "Don't count on it.",
      "My reply is no.",
      "My sources say no.",
      "Outlook not so good.",
      "Very doubtful."
    ]
    const number = Math.floor(Math.random()*20);
    res.status(200).send(answers[number]);

stats.js文件

class StatsPage extends Component {
  render() {
    return (
      <main>
        <Header />
          <h1>Game Statistics</h1>
          <p> Count: </p>
          <style jsx>{`
            h1 {
              font-family:"Arial";
              font-size:50px;
            }`}
          </style>

      </main>
    )
  }
}

export default StatsPage;

我的问题是:每次在index.js文件中按下按钮(即询问问题)时,如何在stats.js中渲染计数器变量?我应该使用saveToLocalStorage来确保计数器保持其状态,并且每次刷新应用程序时都不会恢复为零吗?

此外 - 如果有人有任何改进意见,请分享!

谢谢你的时间。

javascript node.js reactjs client-server
1个回答
1
投票

如果您不熟悉React和JavaScript,最好使用localStorage。这是解决问题的最简单的解决方案,并且是一种在刷新浏览器时停止应用程序状态消失的好方法。

像这样的需要跨页面共享的状态可以保存在包含两个页面组件的父组件中。然后,父组件可以将状态作为props传递给子组件。此父组件也可以尝试在安装时从localStorage加载其初始状态(请参阅componentDidMount),并处理将状态写入localStorage。

Here's a jsfiddle有一个我上面描述的非常简单的例子。

作为附注,我看到您使用action属性处理表单提交。这将导致您的页面刷新,这可能不是您想要的。处理这种情况的React方法是使用onSubmit<form>道具。见examples in the React docs

© www.soinside.com 2019 - 2024. All rights reserved.