如何在React(Gatsby)中使用staticman?

时间:2019-02-27 05:27:21

标签: reactjs forms gatsby

如此处https://github.com/eduardoboucas/staticman/issues/243所述 ,staticman通过其集中式API无法使用,因为已达到一定的配额

正因为如此,staticman成为了 github应用来扩展这些配额,但是仍然没有正式的文档来运行它。

这是怎么做的?

1 个答案:

答案 0 :(得分:1)

基于https://github.com/robinmetral/eaudepoisson

  1. 创建github存储库
  2. 在该存储库中安装staticman应用,此处https://github.com/apps/staticman-net
  3. 在存储库的根目录中创建一个配置文件staticman.yml,查看配置https://staticman.net/docs/configuration的文档 并在仓库https://github.com/robinmetral/eaudepoisson

重要的是,staticman.yml的属性名称是comments:,该属性就是您回购的方向。因此,如果您要将注释发送到your_repo/markdown/website_comments,则path中的staticman.yml应该是path: "markdown/website_comments"),但是下面看到您的url不引用文件夹结构而是转到staticman.yml属性

  1. 在您的存储库中创建一个/markdown/website_comments文件夹(并非必要,该文件夹结构将使用第一个注释创建)
  2. 创建一个form,我已经完成了react.semantic-ui.com提供的表单
<Form onSubmit={onSubmit}>
    <Form.Input name="name" onChange={changeUserName} placeholder="what" />
    <Form.TextArea name="message" onChange={changeuserMessage} placeholder="what2" />
    <Form.Button>Submit</Form.Button>
</Form>
  1. 添加发送前一个表单的逻辑,其中formdata发送到https://dev.staticman.net/v3/entry/github/ {我的github用户} / < strong> {我的仓库} /master/comments/(更改github用户和仓库名称)
  const [userName, setUserName] = useState(() => '')
  const [userMessage, setUserMessage] = useState(() => '')
  const wait = ms => new Promise((r, j) => setTimeout(r, ms))

  let changing = 0 // to create a buffer to avoid changing state always, the browser gets slow otherwise
  const changeUserName = async (e, { value }) => {
    changing++
    let prev_changing = changing
    await wait(100)
    if (prev_changing === changing) setUserName(value)
  }

  const changeuserMessage = async (e, { value }) => {
    changing++
    let prev_changing = changing
    await wait(100)
    if (prev_changing === changing) setUserMessage(value)
  }

  const onSubmit = async e => {
    e.preventDefault()
    const formdata = new FormData()
    formdata.set('fields[name]', userName)
    formdata.set('fields[message]', userMessage)
    const json = {}
    formdata.forEach((value, prop) => (json[prop] = value))
    const formBody = Object.keys(json)
      .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(json[key]))
      .join('&')

    // in the repo, create a folder named 'comments'
    const response = await fetch(
      'https://dev.staticman.net/v3/entry/github/{my github user}/{my repo}/master/comments/',
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formBody,
      }
    )
    console.log(response)
  }

就是这样,或者至少它似乎在我手中起作用