我正在从https://github.com/moroshko/react-autosuggest实现一个示例
重要代码如下:
import React, { Component } from 'react';
import suburbs from 'json!../suburbs.json';
function getSuggestions(input, callback) {
const suggestions = suburbs
.filter(suburbObj => suburbMatchRegex.test(suburbObj.suburb))
.sort((suburbObj1, suburbObj2) =>
suburbObj1.suburb.toLowerCase().indexOf(lowercasedInput) -
suburbObj2.suburb.toLowerCase().indexOf(lowercasedInput)
)
.slice(0, 7)
.map(suburbObj => suburbObj.suburb);
// 'suggestions' will be an array of strings, e.g.:
// ['Mentone', 'Mill Park', 'Mordialloc']
setTimeout(() => callback(null, suggestions), 300);
}
该示例中的复制粘贴代码(有效)在我的项目中出现错误:
Error: Cannot resolve module 'json' in /home/juanda/redux-pruebas/components
如果我拿出前缀json !:
import suburbs from '../suburbs.json';
这样,我在编译时不会出错(导入已完成)。但是执行时出现错误:
Uncaught TypeError: _jsonfilesSuburbsJson2.default.filter is not a function
如果我调试它,我可以看到郊区是一个对象,而不是一个数组,因此未定义过滤器功能。
但是在示例中,注释建议是一个数组。如果我像这样重写建议,那么一切都会起作用:
const suggestions = suburbs
var suggestions = [ {
'suburb': 'Abbeyard',
'postcode': '3737'
}, {
'suburb': 'Abbotsford',
'postcode': '3067'
}, {
'suburb': 'Aberfeldie',
'postcode': '3040'
} ].filter(suburbObj => suburbMatchRegex.test(suburbObj.suburb))
所以...什么json!前缀是在导入吗?
为什么不能将其放入代码中?一些babel配置?