如何更改 React 地图中的渲染顺序

How to change order of rendering in a React map

我的任务很简单,我觉得这个问题的答案也很简单。但出于某种原因,我无法理解它。我应该从数据库中获取问题列表并将它们显示在网站上。这个特定的部分是是或否的问题。当我从数据库中获取问题时,大多数问题已经按顺序排列,"yes" 然后是 "no"。但是,有一个被翻转了。所以我的问题是,如何将颠倒的顺序翻转到正确的顺序?

老实说,我并没有尝试太多,因为就像我说的,出于某种原因我无法理解它。但我确实知道在数据库中,问题有一个名为 order 的字段,其中 yes 是 0,no 是 1。所以我猜我必须以某种方式使用它。

这是我呈现问题的代码,

{state.surveyQuestions.map(question => (
    <span key={question.question.id}>
        <FormLabel className={classes.label} component="legend">{question.question.label}</FormLabel>
        <RadioGroup value={state.consent} onChange={handleChange} style={{ height: 'auto', padding: '10px' }}>
            {question.question.choices.items.map(choice => (
                <FormControlLabel key={choice.order} style={{ paddingTop: '1px' }} value={choice.value} control={<Radio />} label={choice.label} />
            ))}
        </RadioGroup>
    </span>
))}

这是来自数据库的内容,

"choices": {
    "items": [
        {
            "label": "No",
            "value": "{\"value\":\"0\"}",
            "dataUID": null,
            "description": "No",
            "order": 1,
            "goto": null
        },
        {
            "label": "Yes",
            "value": "{\"value\":\"1\"}",
            "dataUID": null,
            "description": "Yes",
            "order": 0,
            "goto": null
        }
    ]
}

使用Array.protoype.sort()用自定义函数对'choices'进行排序;

const data = [
    {
        "label": "No",
        "value": "{\"value\":\"0\"}",
        "dataUID": null,
        "description": "No",
        "order": 1,
        "goto": null
    },
    {
        "label": "Yes",
        "value": "{\"value\":\"1\"}",
        "dataUID": null,
        "description": "Yes",
        "order": 0,
        "goto": null
    }
];

// Full function for readability
function orderByOrderValue( a, b ) {
  if ( a.order < b.order ){
    return -1;
  }
  if ( a.order > b.order ){
    return 1;
  }
  return 0;
}

console.log(data.sort(orderByOrderValue));

// Or use the one-liner
// data.sort((a,b) => (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0)); 

您可以使用选项的 order 属性进行排序,即 choices.items 在呈现选项时

您可以轻松实现 sort 功能:

data.sort((a, b) => a.order - b.order);

If compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first).

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different
elements. Note: the ECMAscript standard does not guarantee this
behavior, thus, not all browsers (e.g. Mozilla versions dating back
to at least 2003) respect this.

If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first).

按照这些规则,如果用下一个元素减去第一个出现的元素的顺序,您将获得排序函数的正确输出。