小编pet*_*176的帖子

React Typescript:添加位置状态以响应路由器组件

我有一个正常的路线

function LoginPage(props: RouteComponentProps): React.ReactElement {...
}
Run Code Online (Sandbox Code Playgroud)

使用RouteComponentPropsfrom react-router-dom.

奇怪的是有很长一段时间,这部分没有问题,但现在却未能收集关于特拉维斯-CI,当我使用history.push(location.state.from.pathname)Property 'from' does not exist on type '{}'.

我在我的 PrivateRoute 组件中设置了这个状态,这是非常标准的重定向

<Redirect
  to={{ pathname: '/login', state: { from: props.location } }}
/>
Run Code Online (Sandbox Code Playgroud)

如何更新输入location以包含from对象pathname: string;

编辑:

解决方案是添加

COPY yarn.lock /usr/src/app/

在我复制 package.json 之后到我的 Dockerfile。

typescript docker reactjs react-router

10
推荐指数
3
解决办法
2万
查看次数

Go websocket错误:close 1006(异常关闭):意外的EOF

我正在尝试使用 gorilla/websocket 编写一个简单的 go websocket 服务器

http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
    if os.Getenv("env") == "development" {
        upgrader.CheckOrigin = func(r *http.Request) bool { return true }
    }

    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Printf("Websocket error: %s", err)
        return
    }

    defer conn.Close()

    // Register client
    clients[conn] = true

    for {
        message := message.Message{}
        _, msg, err := conn.ReadMessage()
        if err != nil {
            log.Printf("Websocket error: %s", err)
            return
        }

        res, _ = json.Marshal(context.Game)

        // Send to …
Run Code Online (Sandbox Code Playgroud)

go websocket

9
推荐指数
1
解决办法
3万
查看次数

Django Rest Framework-提交的数据不是文件。检查表单上的编码类型

我有一个关于文本字段的React Axios帖子,但是现在我想在模型中添加图像字段。

这是我在图像字段中的新模型:

def get_image_path(instance, filename):
    return os.path.join('posts', str(instance.author), filename)


class TripReport(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    countries = models.ManyToManyField(Country, blank=False, related_name='trip_countries')
    title = models.CharField(max_length=100)
    content = models.TextField()
    image = models.ImageField(upload_to=get_image_path, null=True, blank=False)
    date_posted = models.DateTimeField(default=timezone.now)
    slug = models.SlugField(max_length=12, unique=True, blank=True)
    favoriters = models.ManyToManyField(User, related_name='favoriters')
Run Code Online (Sandbox Code Playgroud)

我用这个从我的表单中拉出文件:

e.target.image.files[0]
Run Code Online (Sandbox Code Playgroud)

它将记录如下文件对象:

{ name: "DSCF6638.JPG", lastModified: 1340012616000, webkitRelativePath: "", size: 5395895, type: "image/jpeg" } 
Run Code Online (Sandbox Code Playgroud)

当我进行控制台登录时。

我已经将image变量添加到axios的POST请求中:

export const postTripReport = (author, title, content, countries, image) => {
  const token = localStorage.getItem('token');
  return dispatch => { …
Run Code Online (Sandbox Code Playgroud)

django-rest-framework reactjs axios

7
推荐指数
1
解决办法
1610
查看次数

如何在 React 中将 props 传递给 Jest 测试

我是 React 和测试的新手。我正在尝试测试具有条件渲染的组件:

render() {
if (this.props.fetched === true){
  return (
    <div className="search">
      <div className="">
        <SearchBar getCountry={this.getCountry} /> <br/>
        <Results country={this.props.country}/>
      </div>
    </div>
  );
} else { return (
    <div className="search">
      <div className="">
        <SearchBar getCountry={this.getCountry} /> <br/>
      </div>
    </div>
)}
Run Code Online (Sandbox Code Playgroud)

} }

在我的测试中,我试图将 this.props.fetched 传递到包装器中以测试在 fetched=true 之后显示的内容。现在这是我的测试:

it('renders results after search', () => {
  const fetched = true;
  const wrapper = shallow(<Search store={store} {...fetched}/>);
  expect(wrapper.find('Results').length).toEqual(1);
});
Run Code Online (Sandbox Code Playgroud)

但是我的测试一直失败,所以我不能传递道具。这样做的正确方法是什么?谢谢!

reactjs jestjs enzyme

5
推荐指数
1
解决办法
7580
查看次数

使用酶测试无状态React组件中的功能

我有一个无状态组件:

export default function TripReportFooter(props) {
  const { tripReport, user, toggleFavorite, navigation } = props;


  handleShare = async slug => {
    try {
      const result = await Share.share({
        message: `Check out this Trip Report:\n/p/${slug}/`
      });

      if (result.action === Share.sharedAction) {
        if (result.activityType) {
        } else {
          // shared
        }
      } else if (result.action === Share.dismissedAction) {
      }
    } catch (error) {
      alert(error.message);
    }
  };

  handleFavorite = async id => {
    const token = await AsyncStorage.getItem("token");
    toggleFavorite(id, token);
  };

  return ( …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-native enzyme

5
推荐指数
1
解决办法
2394
查看次数

DRF在create()方法中返回序列化对象

我正在为我的模型编写一个自定义创建方法:

class TripReportViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    serializer_class = TripReportSerializer
    pagination_class = TripReportSetPagination
    # To order by favorite count or 'top':
    queryset = TripReport.objects.all().annotate(count=Count('favoriters')).order_by('-count')
    #queryset = TripReport.objects.all().order_by('-pk')
    filter_backends = (filters.SearchFilter, filters.OrderingFilter)
    search_fields = ('=author__username', '=slug', 'countries__name', )
    ordering_fields = ('pk', )

    def create(self, request, **kwargs):
        countries = request.POST['countries'].split(',')
        countries = list(map(int, countries))
        countries = Country.objects.filter(pk__in=countries)

        instance = TripReport.objects.create(
            author=User.objects.get(pk=request.POST['author']),
            title=request.POST['title'],
            content=request.POST['content'],
        )
        instance.countries.set(countries)
        instance.save()
        return HttpResponse(TripReportSerializer(instance))
Run Code Online (Sandbox Code Playgroud)

我似乎无法得到正确的回应。我想返回我的序列化对象,但是

HttpResponse(instance)
Run Code Online (Sandbox Code Playgroud)

HttpResponse(TripReportSerializer(instance))
Run Code Online (Sandbox Code Playgroud)

给了我错误的结果。TripReportSerializer 是我用于视图的一个。

python django-serializer django-rest-framework

4
推荐指数
1
解决办法
3850
查看次数

React Native 在滚动视图中延迟加载 250 张图片

我有 250 个对象处于状态,我试图在滚动视图中加载每个对象的图像。我正在使用 react-native-lazyload,它适用于大约前 75 张图像,然后滚动开始减慢到停止,几乎每次都在同一位置。

有没有其他方法可以加载这些图像?似乎 Flatlist 比 Scrollview 更好,但我没有可以调用 onEndReach 的函数

reactjs react-native react-native-flatlist

4
推荐指数
1
解决办法
8518
查看次数

Django rest-auth 令牌认证

我正在尝试使用 axios 从 /rest-auth/user/ 页面获取信息。这是我的功能:

export const fetchUser = () => {
  const token = localStorage.getItem('token');
  return dispatch => {
    dispatch(fetchUserPending());
    axios.get('http://localhost:8000/api/v1/rest-auth/user/', {headers: { 'authorization': `Bearer ${token}`}})
      .then(response => {
        const user = response.data;
        dispatch(fetchUserFulfilled(user));
      })
      .catch(err => {
        dispatch(fetchUserRejected(err));
      })
  }
}
Run Code Online (Sandbox Code Playgroud)

它使用我从登录中获得的 django 令牌,该令牌存储在 localStorage 中。我收到错误状态 403,未提供身份验证凭据。我试过编辑我的 django settings.py 文件以包含

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': [
       'rest_framework.authentication.TokenAuthentication',
   ],
} 
Run Code Online (Sandbox Code Playgroud)

然后我收到未经授权的错误代码 401。任何人都可以指导我朝着正确的方向前进吗?谢谢!

django django-rest-framework reactjs react-redux axios

2
推荐指数
1
解决办法
1181
查看次数

将函数传递到React Navigation的headerTitle组件中

我正在尝试实现deletePost按钮,但是我正在努力将其传递到我的标头组件中。这是

export class PostScreen extends Component {


  // Custom headerTitle component.
  static navigationOptions = ({ navigation }) => {
    const { params } = navigation.state;
    return { headerTitle: <PostTitle {...params} handleDelete={this.handleDelete}/> }
  };

  handleDelete = async (id) => {
    const { deletePost } = this.props;
    const token = await AsyncStorage.getItem('token');
    deletePost(token, id);
  }

render() {
Run Code Online (Sandbox Code Playgroud)

这似乎不是传递它的正确方法。正确的方法是什么?我在文档中找不到任何内容。

reactjs react-native react-navigation

2
推荐指数
1
解决办法
1662
查看次数

React/Jest/Enzyme - 等待时间不够长

我有一个等待多个承诺的函数

const function = async () => {
    await function1()
    await function2()
    await function3()
}
Run Code Online (Sandbox Code Playgroud)

我想测试 function3 被调用:

it(('calls function3', async () => {
    jest.spyOn(api, 'function1').mockResolvedValue({})
    jest.spyOn(api, 'function2').mockResolvedValue({})
    spy = jest.spyOn(api, 'function3')
    await function()
    expect(spy).toBeCalledTimes(1)
})
Run Code Online (Sandbox Code Playgroud)

这个测试失败了,但是当我多次调用 await 时:

it(('calls function3', async () => {
    jest.spyOn(api, 'function1').mockResolvedValue({})
    jest.spyOn(api, 'function2').mockResolvedValue({})
    spy = jest.spyOn(api, 'function3')
    await await await await await function()
    expect(spy).toBeCalledTimes(1)
})
Run Code Online (Sandbox Code Playgroud)

测试将通过。为什么是这样?await function()在进入下一个期望行之前不应该解决所有的承诺吗?

编辑:等待的函数越深,即函数 4,我需要的等待语句越多,但它不是 1 比 1。

javascript ecmascript-6 reactjs jestjs enzyme

2
推荐指数
2
解决办法
4192
查看次数

如何在React中使用.join()如果数组最初不存在

我有一个功能反应组件,在api请求后显示信息.最初它显示的对象是空白的,因为尚未提出请求.在该对象中是一个如下所示的数组:

['US', 'USA', 'United States of America']
Run Code Online (Sandbox Code Playgroud)

当我只是显示数组时,在api请求之后,它在页面上显示为单个字符串,ex之间没有空格:

USUSAUnited States of America
Run Code Online (Sandbox Code Playgroud)

当然,我想用.join(',')来格式化它,以格式化美国,美国,美国等字符串,但在我添加.join(',')后,它会抛出一个错误:

TypeError: props.modalCountry.alt_spellings is undefined
Run Code Online (Sandbox Code Playgroud)

似乎.join()试图在有一个实际的modalCountry对象之前在第一个渲染上运行.在对象和数组实际存在之前,如何让此方法不运行?

javascript ecmascript-6 reactjs

0
推荐指数
1
解决办法
98
查看次数