翻译数据动态反应本地化redux

时间:2018-08-23 15:34:28

标签: javascript reactjs

我已经浏览过文档以对本地化的还原进行反应-https://ryandrewjohnson.github.io/react-localize-redux-docs/

我设法得到一个简单的示例,但是我不知道如何将它与对我有用的json数据结构一起使用,而不是将它们用作示例。

例如,我希望将“ reviews”作为一个数组,以便可以使用相同的键id,但是这样做时,我会得到missing translation id错误,这使得以这种方式过滤数据变得很困难我想,例如,我希望能够通过sub进行映射,但是必须命名子项cat1cat2等,以便它们可用于翻译组件中,从而限制了这个

如何更改数据结构以使其更有用并允许我进行映射?

Main.js

import React from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { withLocalize } from 'react-localize-redux'
import globalTranslations from '../translations/global.json'
import { Translate } from "react-localize-redux";
import styled from 'styled-components'
import translations from '../translations/global.json';

const Wrap = styled.div`
  margin: 100px 0 0 0;
  width: 100%;
  height: 100px;
  background: #fff;
  color: #000;

`
class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      reviews: ['cat1', 'cat2'],
    };

    this.props.addTranslation(translations);

    this.props.initialize({
      languages: [
        { name: "English", code: "en" },
        { name: "French", code: "fr" }
      ],
      translation: globalTranslations,
      options: { renderToStaticMarkup }
    });
  }

  render() {
    return(
      <Wrap>
          <Translate>
          {({translate}) =>
            this.state.reviews.map((review, index) =>
              <div key={index}>
                <h2>{ translate(`reviews.${review}.cat`) }</h2>
                <p>{ translate(`reviews.${review}.desc`) }</p>
              </div>
            )
          }
        </Translate>

        <Translate>
          {({translate}) =>
            this.state.reviews.filter(items => 'cat1').map((review, index) =>
              <div key={index}>
                <h2>{ translate(`reviews.${review}.sub.cat`) }</h2>
                <p>{ translate(`reviews.${review}.desc`) }</p>
              </div>
            )
          }
        </Translate>
      </Wrap>
    )
  }
}

export default withLocalize(Main);

global.json

{
  "reviews": {
    "cat1": {
      "cat": ["food and drink", "french food and drink" ],
      "slug": "food-and-drink",
      "desc": ["english", "french"],
      "sub": {
        "cat1": {
          "name": "food 1"
        },
        "cat2": {
          "name": "food 2"
        }
      }
    },
    "cat2": {
      "cat": ["review2" , "french review 2"],
      "slug": "food-and-drink",
      "desc": ["english", "french"],
      "sub": {
        "cat1": {
          "name": "food 1"
        },
        "cat2": {
          "name": "food 2"
        }
      }
    }
  }
}

0 个答案:

没有答案